Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity / RIDER: order of multiplication operations is inefficient?

Tags:

c#

unity3d

rider

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

like image 751
Mark Smith Avatar asked Sep 14 '19 08:09

Mark Smith


1 Answers

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.

like image 191
XenoRo Avatar answered Oct 22 '22 12:10

XenoRo