11

The rider IDE is informing me that the following is inefficient

        transform.Translate(moveDirection * speed * Time.smoothDeltaTime);

and wants to re-write it as

        transform.Translate(Time.smoothDeltaTime * speed * moveDirection);

Anybody know why ?

Its all multiplications, whats the difference ?

For some context, here is the value of speed and moveDirection

private Vector3 moveDirection = Vector3.left;

private float speed = 2.5f;

I am little confused in understanding why its better ?

Can anyone help?

Thanks

Mark Smith
  • 437
  • 1
  • 6
  • 11

2 Answers2

19

Vector3 has 3 components. X, Y and Z.

Multiplying a Vector3 by a value multiplies the components by that value.

Since there are 2 values beside the vector, order matters not for the result, but does for the number of operations.

That is because vector-first will result in 3+3=6 multiplications:

  1. X*=speed
  2. Y*=speed
  3. Z*=speed
  4. X*=time
  5. Y*=time
  6. Z*=time

While vector-last will be 1+3=4 multiplications:

  1. scale=speed*time
  2. X*=scale
  3. Y*=scale
  4. Z*=scale

Either way, it's just Rider being paranoid about performance, and that level of optimization, while always welcome, is definitely not required in most cases.

CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
-1

I think this is the best solution:

transform.Translate(new Vector3(0,0,speed * Time.deltaTime) );

this tells unity to translate an object FORWARD, remember that forwards is this = Shorthand for writing Vector3(0, 0, 1).

so if we go to this statement we must make the multiplications in the last variable number, on the FORWARD in unity is the Z, so this will multiply in the correct fields, and make sense because the other numbers are 0 so if the machine multiply the 0 like 100000000000000 times that's inefficient and that's why RIDER was complaining, thanks