- Home /
One line function and performance.
Hi guys,
For the last week I have been reading about optimization and it has made a huge difference to the speed of my zombie game. One of the things I read was about not repeating lines.
I have a line of code that I use about 4 times in my script that checks distance to the player. So I put the line of code in a function...
function DistanceToPlayer()
{
distanceToPlayer = ( playerTransform.position - zombieTransform.position ).sqrMagnitude;
}
It struck me though that to call a function with one line of code would be less optimal than simply using the line of code where needed. Two operations have to be done instead of one, a call to the function and then execution of the line.
It might be a pedantic question but is it better to simply use the one line of code where needed or put it in a function? Or doesn't it make any difference except for cleaner code?
Many thanks,
Bruce
Answer by Eric5h5 · Dec 18, 2012 at 04:03 AM
It's better to put it in a function, since DistanceToPlayer is more readable than the line of code, and if you change the way it works for whatever reason, you only need to change the code in the function instead of having to change it everywhere. It's true that there is overhead for calling a function, but it's not likely to make any difference unless you're doing it a really large number of times (say, thousands of time in a loop that runs every frame).
There's also a compiler feature known as "function inlining", where even though you write code using functions, the compiler goes and basically replaces function calls with the line of code for you. That way you get the readability and maintenance benefits of writing code using functions, but the performance of using the code directly. The only issue is that Unity doesn't currently actually do function inlining as far as I know, but that could change the next time they update the version of Mono that Unity uses.
Thanks Eric! I had not even considered the changing of the code until you mentioned it, I had been going through and changing every line of code.
Very interesting what you said about the function inlining too. Understanding that will void me needing to ask silly questions again. Hopefully they will implement it as you say. Thanks again :)
Your answer
Follow this Question
Related Questions
Which Unity functions are generally slow/bad for performance? 4 Answers
Performance Optimization ~Function Update: Loop or Once ? 5 Answers
How do I create a function that accepts EITHER vector3 OR three floats? 1 Answer
Using a member variable from one function in another 3 Answers
How to use different types of scripts with an override function. 2 Answers