More efficient bounding box?

I currently have this code snippet running in my compute shader which clamps particles to a region, and bounces them back based on their velocity.

    particles[i].position += particles[i].velocity * deltaTime;
    if (particles[i].position.x > fieldSize) {
        particles[i].position.x = fieldSize;
        particles[i].velocity.x *= -1;
    }
    if (particles[i].position.x < -fieldSize) {
        particles[i].position.x = -fieldSize;
        particles[i].velocity.x *= -1;
    }
    if (particles[i].position.z > fieldSize) {
        particles[i].position.z = fieldSize;
        particles[i].velocity.z *= -1;
    }
    if (particles[i].position.z < -fieldSize) {
        particles[i].position.z = -fieldSize;
        particles[i].velocity.z *= -1;
    }

I was wondering if there’s a better way to do this that’s more efficient, since running this on millions of particles tanks the FPS compared to what I had before, but it didn’t have the restitution effect:

    particles[i].position.x = clamp(particles[i].position.x, -fieldSize, fieldSize);
    particles[i].position.z = clamp(particles[i].position.z, -fieldSize, fieldSize);

Any help would be appreciated!

The logic does what the logic needs to do. I doubt it would make a measurable difference, but you might try v = -v instead of v *= -1.

Ah sorry I should have mentioned, I’ll most likely be adjusting the values for that. The -1s are magic numbers that I need to get rid of.

is array access slow (if in your script try getting those values used multiple times into temp variables first) ?

or using ternaries, would the particles get stuck near edges, if you do abs,
then check max, then flip velocity, (without resetting position)

float vx = particles[i].velocity.x;
float px = particles[i].position.x;
vx = (px < 0 ? -px : px) > fieldSize?-vx:vx;
particles[i].position.x = px;
particles[i].velocity.x = vx;

or add position reset,

float vx = particles[i].velocity.x;
float px = particles[i].position.x;
bool exitMin = px < -fieldSize;
bool exitMax = px > fieldSize;
px = exitMin?-fieldSize:(exitMax?fieldSize:px);
vx = (exitMin|exitMax)?-vx:vx;
particles[i].position.x = px;
particles[i].velocity.x = vx;

These both work great, thank you!