Reputation: 320
I am recently trying to improve the code quality of a side-project and I was wondering something about cache...
Let's suppose we have the following code:
if(a || b)
Now, let's imagine a
and b
are actually very long operations e.g:
element.getValue(anIndexContainer[anotherSubItemCauseReasons])
What I would do is of course to make it readable as, for instance:
bool shouldDoSomething = a || b
// the bool will NEVER be used after the if
if(shouldDoSomething)
My question is: does this consume more cache?
My guess is that since the bool is declared right before the if
and they are never re-used, the compiling optimizes it as it is in the first case.
Is there any evidence/proof/spec about the behaviour C# compiler would have?
FOR FUTURE READERS:
This link is the example of what the compiler does, credits to @stefano balzarotti for the link :)
Upvotes: 0
Views: 85
Reputation: 152566
Is there any evidence/proof/spec about the behaviour C# compiler would have?
To my knowledge, the compiler and the JITter (which transforms compiled byte-code into machine code) can do pretty much anything they want to improve performance that does not change the functional effect of the code. There are flags that will keep the compiler from making these types of optimizations, but that's more for debugging purposes by keeping the byte code more aligned with the source code. Once you tell the compiler to optimize, it's out of your control.
So yes, the compiler (or JITter) might detect that these variables can be in-lined and do so, but why do you care? Write the source code in a way that makes logical sense, so others that maintain it (or you after a few months) know what the heck you intended to do. Only if you have measurable performance problems should you try to outsmart the compiler.
This might be applicable in lower-level languages where registers or stack space is taken up, but in high-level managed languages these aren't huge concerns.
Upvotes: 2