Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Worth it to convert 3D to 2D for Vector2.Dot product?

Discussion in 'Scripting' started by Gordon_G, Jul 6, 2020.

  1. Gordon_G

    Gordon_G

    Joined:
    Jun 4, 2013
    Posts:
    358
    Hey all, is it worth it from a performance standpoint to extract the xz components of 3D vectors and then use them in Vector2D.Dot rather than Vector3.Dot?

    I've got a racing game ranking system on a flat road that uses the dot product as a part of a function that calculates the distance to way point lines. So I really only need the distance calculations in 2D.

    So I think for each horse in the race, we'd have in short strokes:

    given v1 is a 3D direction vector of a horse, and the line normals precalculated at Start():

    Vector3.Dot( lineNormal3D, v1.normalized )

    vs.
    Vector2 v3 = new Vector2( v1.x, v1.z )
    Vector2.Dot( lineNormal2D, v3.normalized )


    Would I be saving anything performance wise?
     
  2. Mariusz_H

    Mariusz_H

    Joined:
    May 4, 2018
    Posts:
    18
    Don't waste your life optimizing such small things :) Today code performance is bound mostly by processor cache misses, not computation capacity.
     
    Gordon_G likes this.
  3. Gordon_G

    Gordon_G

    Joined:
    Jun 4, 2013
    Posts:
    358
    Of course, understood. My question is more from an academic standpoint.

    That said, as the geme is being created for mobile devices, and there are several dot products that are calculated for each horse each and every frame, we may have to squeeze every ounce of performance out of the code where we can.

    So, do you have an answer or not?
     
  4. Mariusz_H

    Mariusz_H

    Joined:
    May 4, 2018
    Posts:
    18
    Vector2 will be faster than Vector3 (especially if you do calculations in place). If you use float2, native array and burst it could be nicely vectorized and even faster.

    But it is not worth your time. Horse races have 12 horses max so performance gain will be just noise on multi-core device.
     
    Last edited: Jul 6, 2020
    Gordon_G likes this.
  5. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,920
    You could have horses only use Vector2: only convert to Vector3 position once each frame. That also saves remembering "y is z" in all of the movement code. But have to be careful. An accidental v2 into a v3, transform.position=horsePosV2, is legal in Unity. When Unity decided 2D used xy I thought "that's dumb, everyone knows Unity ground is xz". Now I realize it was a good call.

    But dot-product isn't that bad: the dead y=0 is 1 extra multiply and add. Sure, without it is 30% faster, but 30% of "not much. It's like buying shoelaces at a 30% discount but not getting a deal on shoes.
     
    Gordon_G likes this.