Definitely do not try to optimise this. Do not!
Go for what is easier to read. Technically there is an overhead with calling a function and technically there is an overhead with checking an if that turns out to be false but it is not worth trying to optimise this.
if (a) {
b = !b;
}
if (b)
DoSomething();
else
DoSomethingElse();
while method 3 does this:
if (a) {
b = !b;
if (b)
DoSomething();
else
DoSomethingElse();
}
Method 3 is obviously a lot better from a performance standpoint. It’s not going to make much of a difference in your example since you’re not doing much, but on a general basis, you shouldn’t keep setting the same values to the same thing again and again.
The instinct to split things into methods for readability from your method 1 is a good one, you’re just doing it in a wonky way. I’d just do:
private void Update()
{
if (Input.GetKeyDown("p")) {
TogglePause();
}
}
private void TogglePause() {
paused = !paused;
if (paused) {
// do the paused thing
}
else {
// do the unpaused thing
}
}
As people are saying upthread, worrying too much about optimization could lead to bad productivity and bad code, but in this case there doesn’t need to be a trade-off.
Thank you sir. This is a simple example for understanding what i have to do. I want to optimize my project (almost 7000 lines of code), but I can’t put all my code here and ask for optimization, that is why i wrote a simple example.
If not, there’s not really any reason to optimize. I mean, unless you find it fulfilling, in which case go right ahead.
If you are having performance problems, you should profile the game to figure out what’s going wrong instead of trying to do general optimizations. Unity has a very good built-in profiler.
Yes, I have some performance problems. But my cod is like i wrote it with my legs. I want to rewrite the code and after this to use profiler if i will have performance problems.
I’d like to Point out that Method 3, while perhaps faster, is logically very different, as the inner part is only executed when a is true. So, Method 3 has no equivalent in 1 or 2.
But I agree with Baste’s (MUCH) bigger Point that you should not try to optimize Update() blindly, but use the profiler to identify low-hanging fruits.