I have a function that has a large number if individual input parameters, the function is also run hundreds of millions of times during the program.
If i wanted to optimize this function, should I create a new data structure that holds all the input parameters and pass it to the function by reference instead of passing each parameter individually to the function? Or would it not matter because the compiler is smart enough to deal wit this in an even more efficient manner?
In general, it’s much better to pass a data structure that contains your variables. This isn’t pretty to look at or use:
This is much nicer:
You may want to do pass by reference, so the compiler can just pass a reference to the object, and not copy the entire data structure.
As a real example:
It would be better if encapsulated our (x, y, z) into a data structure though:
Much cleaner code, and you get the added bonus that it could* perform better (*Depending on how smart your compiler is at optimizing either version).
Obviously this could vary wildly depending on what you’re actually trying to accomplish, but if you have several (4+) variables that have a similar usage in a certain context, it may be better to just pass it in a data structure.