Search Unity

Alternative To Define Macros(like C++)

Discussion in 'Scripting' started by z_master, Apr 14, 2019.

  1. z_master

    z_master

    Joined:
    Aug 12, 2015
    Posts:
    2
    Hi guys,

    I'm having some issues with performance in my project, part of them are caused by Vector and Mathf functions, but the problem isn't with the math operations itself, the problem is that they are functions calls, every operation with a Vector is a function call, since the simple calling of a function in C# causes an overhead, if you have a code that requires a lot of them this causes a big impact on fps.
    The obvious solution is to convert these operations to simple math operations like:

    Code (CSharp):
    1. Vector3 result = vectorA+vectorB;
    2. // to:
    3. Vector3 result = new Vector3(vectorA.x+vectorB.x,vectorA.y+vectorB.y,vectorA.z+vectorB.z);
    but the problem is that there are a lot of operations, and they are composed, not only this process will take a lot of time and cause a good amount of bugs during the conversion, as it will make my code terrible to read and to maintain.

    In C++ you can define macros for the preprocessor, if C# had them I could use my own implementations to these functions created as macros, this way the compiler would convert all code to simple math operations and avoid the function call overhead, but C# doesn't have support for macros, does anyone knows an alternative, or have another solution to deal with many Vector operations?
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Can you give some examples of the functions you're calling that are expensive? What's happening in `vectorA + vectorB' that's more expensive than the broken-out approach you want to take?

    One thing to keep in mind is that the order of your terms can have a big impact on performance. For example, the following two statements aren't the same:
    Code (CSharp):
    1. var a = someVector * 2 * 3 * 4;
    2. var b = 2 * 3 * 4 * someVector;
    One of those will results in three Vector3 multiplications, with Vector3 results, while the other will be a single Vector3 multiplication. I've definitely moved some terms around in some of my calculations to multiply all the floats together first, and only apply the product to the Vector3 as the last step.
     
  3. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Another option to mention is that if you're really running into performance issues, you should consider whether you can use Jobs + Mathematics package + Burst Compiler to significantly improve performance. I had some pretty slow code that was doing a lot of raycasting and semi-complex calculations. Putting all of that into Jobs running across multiple threads was definitely a big performance win.