Reputation: 11689
The question is simple, which is faster between CalledOften1 and CalledOften2
class MyTest
{
public bool test = false;
void CalledOften1()
{
if (!test) test = true;
DoSomething();
}
void CalledOften2()
{
test = true;
DoSomething();
}
}
Is the compiler optimized (if possible) to avoid future assignments of test if it's already true?
UPDATE: This question is just an information, I will not use the if (bla) style if I can write test=true, I prefer code readability.
Upvotes: 2
Views: 4862
Reputation: 28991
Premature optimization is the root of all evil. Use the one that expresses your intent most clearly.
(I'm guessing a read+branch is going to be more expensive than just a write, but don't really know the CLR. The important thing is that computers are increasing in speed exponentially, and programmers aren't. Algorithmic improvements in performance bottlenecks are worth exploring, barely measurable constant-time improvements for their own sake aren't.)
Upvotes: -4
Reputation: 838256
I prefer to measure for these sorts of questions rather than guess:
So they are nearly the same. If anything, the simpler method is also the faster.
Upvotes: 8
Reputation: 1500665
I would expect the second version to be slightly faster, given that it doesn't involve any branching. It also expresses the intention of "make sure the variable is true, whatever it was before" more clearly IMO. However:
Upvotes: 3
Reputation: 564413
This is a perfect example of premature optimization.
If you want to set test
to true
every time, just set it. Don't complicate your code for a theorized speedup.
That being said, the reduced instruction set of the second example, along with being simpler and more maintainable, is most likely faster due to avoiding the branching and reducing the number of instructions. A single assignment of a bool
is a very fast operation. If you really need to know how much faster it may be, I would profile this yourself. However, I suspect that either would be fast enough in any case.
Upvotes: 2
Reputation: 12596
If I had to guess, I would say that CalledOften2 is more optimized, as there is no logic test operation done.
In the end, if you are looking at this level of optimization, then your application will probably go as fast as it can. Any performance gain you get out of this type of optimization will likely never be noticed by anyone.
My two cents, Brian
Upvotes: 1
Reputation: 60065
Compiler optimizes only something that is definite at compile time. This is changed at runtime so answer is no. Compiler could optimize if you were checking against constant. CalledOften1
is faster, but the magnitude is so small that you would not notice. This is kind of microptimisation you should avoid.
Upvotes: 1