Performance coding and using 'ref' for method parameters

I’ve just learnt about ‘ref’ for parameters when calling methods which connects back to my olden days of C programming and pointers. Is there any advantage in using it and saving a data copy when calling methods (particularly for mobile0, or does it not make much difference save for large datasets? eg.

public int DoStuff (Vector3 v1, Vector3 v2, Vector3 v3){
    int gems;
    gems = v1.x + v2.x;
    gem -= v3.y;
    other stuff;
    return gems;
}

Will this run any amount faster (if called a zillion times a second) if the parameters were

(ref Vector3 v1, ref Vector3 v2, ref Vector3 v3)?

I appreciate passing by ref means you can screw up the inputs and is DANGEROUS, but performance code is all about running close to the wind to run as fast as possible. :wink: However, if modern CPU caches and compilers can process it just as fast, there’s no point in overcomplicating things.

Yes, it will run faster… But not in any noticeable way under the millions of times per frame. I think the last time I saw it it was in the range of 0.3-0.4 ms per millions of occurrence? Not sure, someone could surely find back those benchmark. It depends mainly to the number of values passed around.

Usually, using ref on struct while passing them to a method is a bad form, as it allows the method to modify the original struct. If you think that you are at the point where this kind of optimization is needed… It’s because you have much bigger design issue to solve first.

The exception to this would be voxel engines IMO. Every nanosecond there counts as possibly millions of voxels have to be progressed in a very short period of time. Cutting down the calculation time (next to having a good code structure and program flow with multithreading) is essential to keep a voxel engine running at interactive speeds.

I found out about ‘ref’ wanting to update an array of data. Trying to find a way to return it (more than one return value per method), I came across ‘out’ and then ‘ref’, and passing the actual array of objects for read-only operations makes a lot of sense to me. More than copying the array every time!