Code is read more often then updated. Writing more readable code is better than writing powerful and geeky code when compilers can optimize for best execution.
For example see below code - this code can be compressed by combining the nested if statements, but will the compiler not optimize this code for best execution anyway while we get to maintain the readability of it?
// yeild sunRays when sky is blue.
// yeild sunRays when sky is not blue and sun is not present.
if (yieldWhenSkyIsBlue)
{
// if sky is blue and sun is present -> yeild sunRaysObjB.
if (sunObjA != null)
{
yield return sunRaysObjB;
}
else
{
// do not yield ;
}
}
else
{
// if sky is not blue and sun is not present -> yeild sunRaysObjB.
if (sunObjA == null)
{
yield return sunRaysObjB;
}
}
As opposed to something like this :
// yeild sunRays when (sky is blue) or (sun is not present and sky is blue).
// (this interpretation is a bit misleading as compared to first one?)
if(( sunObjA == null && yieldWhenSkyIsBlue ==false) || (yieldWhenSkyIsBlue && sunObjA != null) )
{
yield return sunRaysObjB;
}
Reading the first version depicts the use case better for future enhancements\updates ? The second version of the code is shorter but reading it does not make the use case very apparent or does it ? Are there other advantages of second case apart from concise code ?
update #1 : yes it returns ObjB in both cases but based on the condition it may not yield at all. so the strategy decides when to yield and when not. ( one more reason why readability is imp)
update #2 : updated to site a better example. copied the syntax from stripplingWarrior
update #3 : updated for "What do you expect to happen when the sun is out and the sky is blue".
I think the second code example is much more readable, and has the advantage of being pretty optimal anyway.
Most programmers will find this logic flow to be obvious and natural: you will return ObjB if ObjA is null, or if it's not null and howtoYieldFalg is set.
But if I had to choose between making code like this more readable and making it optimal, I'd make it readable first. Only if I discovered that it's the source of a bottleneck would I bother optimizing it. In this particular case, I can pretty much guarantee that your use of yield return will introduce way more overhead than a suboptimal evaluation of your conditionals.
Update
Take another look at your code samples: they are not logically equivalent. What do you expect to happen when the sun is out and the sky is blue? The second code sample correctly allows sun rays to shine in that case, whereas the first example does not.
The fact that it was so easy to introduce a bug in the first case which so many people failed to catch for so long should be ample evidence to show that the second approach is better. All those nested if/else statements can be tricky to keep straight, even to an experienced programmer. Simple boolean logic is a lot easier to keep straight, especially once you use variable names that give it meaning.
Update 2
Based on the further explanation, and with a little creativity, I'm going to suggest an approach that uses both comments and variable names to increase clarity:
/* Explanation: We live on a strange planet where the sun's
* rays can shine if the sky is blue while the sun is out,
* or if the sky is not blue and there is no sun. */
bool sunIsPresent = sunObjA != null;
if ((skyIsBlue && sunIsPresent) ||
(!skyIsBlue && !sunIsPresent))
{
yield return sunRaysObjB;
}
The compiler optimizes right through any way you organize your program's control flow, so you really do not have to worry about it.
The weakness of compilers though, is they only optimize based on preserving code semantics, not preserving the meaning you intend. I compiled both your examples in LLVM, and here are the control flow graphs generated:
and
I was surprised to find the two CFG's are slightly different. You will note that first is an instruction smaller, but in the second graph, there exists a path to the exit node which only passes through one comparison, whereas in the first, two comparisons are always necessary.
In fact, further tracing of possible routes yields that the first example has possible routes of 6,8,8,6 instructions long, while the second has routes of 8,10,10 respectively. In BOTH cases the average run length is 7 instructions long, but we can see that the first case has better best-time run lengths. Without more information the compiler cannot tell which is better.
tldr: Compilers do magic stuff, don't worry about it, code how you think is best.
This is probably not the popular opinion but I'd definitely not rely on the compiler to perform optimizations of this type. (It may do it, I don't know.) I don't see the second example as geeky - for me it describes more clearly that the two conditions are connected.
Typically I try to write as optimal code as possible without making it very cryptic and then let the compiler optimize that.
Though I haven't tested this particular case, I'm willing to bet that there will be no significant difference between the generated code, if any at all.
Unless you're doing it for fun or a specialized use case, I would argue human-readability is by far the more important quality of good code. The compiler is going to collapse much of your expressive code into more efficient forms, and what it misses you probably won't ever notice.
Given that, idiomatic code is easier to read even when it's less concise. Experienced readers of a language are going to recognize a common pattern more quickly than unfamiliar code that is, arguably 'more human' but breaks the familiar pattern. Looping/incrementing constructs are a good example of code that should be unsurprising. So, my approach is: Be expressive but not too clever.
Related
Can I switch a boolean with one statement as effectively as with an if/then/else ?
Found this in another piece of code that is going into my app...
private void whatever()
{
////
//// a bunch of stuff
////
if (SomeBooleanValue)
{
SomeBooleanValue= false;
}
else
{
SomeBooleanValue = true;
}
}
Out of curiosity, I tried this...
private void whatever_whatever()
{
////
//// the same stuff
////
SomeBooleanValue = !SomeBooleanValue;
}
...and walked through it in debug, and it appears that I get the same result.
Is there a good reason to use the if/then/else instead of the single line way ?
Is there a good reason to use the if/then/else instead of the single line way
Not any that I can think of. Using the ! operator is cleaner and more intuitive for most programmers.
The 1-line way is perfectly fine, and the only reason why you'd use the if/ else structure is if you were doing other things aside from just toggling the boolean.
I would say the second one is better since it is more readable and compact (if/then/else IMO just adds unnecesary lines of code), that would be the only (but strong!) reason to prefer one from the other
Due to compiler optimizations, it will be the same as using the ! operator, which is easier to read for other programmers.
However,
To improve performance, the CPU will try to predict the execution logic ahead of time. For conditional (if/else) statements, it will try to predict the result of the condition and then load the rest of the logic. If it chooses incorrectly, it must go back and re-calculate everything again, hence decreasing performance.
http://en.wikipedia.org/wiki/Branch_predictor
Please, please, please write the code as a negation; it is the most succinct and concise expression of intent. If you write the code the first way, every reader of your code is going to waste time wondering why you did NOT write the simple negation.
Most code will be read, by you and others, many more times than it is written. Writing code that eases the reading process is, almost by definition, good code.
Which of these will perform better if we assume that the IF block in #1 will be executed more and less in #2
foreach()
{
if
{
block here
}
}
or
foreach()
{
if !( )
continue
}
I've structured #2 to take the if conditional less often. But, i wanted to know if this was necessary or even helpful.
In each case, the condition will be tested. If the condition is "false", then in #1, it will skip to the end of the if block (and hence move to the next foreach item), and in #2, it will execute "continue", which does essentially the same thing.
The frequency of true/false should have no impact on this.
It generates almost exactly the same IL. Even if there was a difference, it would be so minuscule you would not be able to measure a performance delta.
I would choose one by a desire for cleanliness, not performance. The 'continue' keywork, much like the 'break' statement, can often be overlooked by other developers maintaining the code. This is especially true in more verbose foreach loops with lots of code. For this reason I prefer using the nested if then do rather than if ! continue.
Both codes are equivalent.
Don't forget that the CPU will not run your C# code.
First your C# code will be compiled into IL. It is quite possible that both codes will end up producing the same IL.
Then the IL will be compiled into machine code in a CPU-specific way.
Then the CPU will run the machine code instructions out-of-order using branch prediction. It is quite possible that the 'if' costs zero cycle because of the branch prediction.
If you want to do more of a functional approach, pull the conditional completely out of the loop like this (requires Linq):
foreach(var item in MyEnumeration.Where(x=> /* conditional on x */))
{
}
I've been poking around mscorlib to see how the generic collection optimized their enumerators and I stumbled on this:
// in List<T>.Enumerator<T>
public bool MoveNext()
{
List<T> list = this.list;
if ((this.version == list._version) && (this.index < list._size))
{
this.current = list._items[this.index];
this.index++;
return true;
}
return this.MoveNextRare();
}
The stack size is 3, and the size of the bytecode should be 80 bytes. The naming of the MoveNextRare method got me on my toes and it contains an error case as well as an empty collection case, so obviously this is breaching separation of concern.
I assume the MoveNext method is split this way to optimize stack space and help the JIT, and I'd like to do the same for some of my perf bottlenecks, but without hard data, I don't want my voodoo programming turning into cargo-cult ;)
Thanks!
Florian
If you're going to think about ways in which List<T>.Enumerator is "odd" for the sake of performance, consider this first: it's a mutable struct. Feel free to recoil with horror; I know I do.
Ultimately, I wouldn't start mimicking optimisations from the BCL without benchmarking/profiling what difference they make in your specific application. It may well be appropriate for the BCL but not for you; don't forget that the BCL goes through the whole NGEN-alike service on install. The only way to find out what's appropriate for your application is to measure it.
You say you want to try the same kind of thing for your performance bottlenecks: that suggests you already know the bottlenecks, which suggests you've got some sort of measurement in place. So, try this optimisation and measure it, then see whether the gain in performance is worth the pain of readability/maintenance which goes with it.
There's nothing cargo-culty about trying something and measuring it, then making decisions based on that evidence.
Separating it into two functions has some advantages:
If the method were to be inlined, only the fast path would be inlined and the error handling would still be a function call. This prevents inlining from costing too much extra space. But 80 bytes of IL is probably still above the threshold for inlining (it was once documented as 32 bytes, don't know if it's changed since .NET 2.0).
Even if it isn't inlined, the function will be smaller and fit within the CPU's instruction cache more easily, and since the slow path is separate, it won't have to be fetched into cache every time the fast path is.
It may help the CPU branch predictor optimize for the more common path (returning true).
I think that MoveNextRare is always going to return false, but by structuring it like this it becomes a tail call, and if it's private and can only be called from here then the JIT could theoretically build a custom calling convention between these two methods that consists of just a jmp instruction with no prologue and no duplication of epilogue.
Yes, I know the wording is hard to understand, but this is something that bugs me a lot. On a recent project, I have a function that recurses, and there are a number of conditions that would cause it to stop recursing (at the moment three). Which of the situations would be optional? (I.E. best performance or easiest maintenance).
1) Conditional return:
void myRecursingFunction (int i, int j){
if (conditionThatWouldStopRecursing) return;
if (anotherConditionThatWouldStopRecursing) return;
if (thirdConditionThatWouldStopRecursing) return;
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
2) Wrap the whole thing in an if statement
void myRecursingFunction (int i, int j){
if (
!conditionThatWouldStopRecursing &&
!anotherConditionThatWouldStopRecursing &&
!thirdConditionThatWouldStopRecursing
){
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
}
3) You're doing it wrong noob, no sane algorithm would ever use recursion.
Both of those approaches should result in the same IL code behind the scenes since they are equivalent boolean expressions. Note that each termination condition will be evaluated in the order you write it (since the compiler can't tell which is most likely), so you will want to put the most common termination condition first.
Even though structured programming dictates the second approach is better, personally I prefer to code return conditions as a separate block at the top of the recursive method. I find that easier to read and follow (though I am not a fan of returns in random areas of the method body).
I would opt for the first solution, since this makes it perfectly clear what the conditions are to stop the recursion.
It is more readable and more maintainable imho.
If it's something that needs to be fast, I'd recommend hitting the most common case as quickly as possible (i.e. put the base case at the end because you'll only hit it once). Also think about putting a base case-1 before the recursing clause (i.e. perform the test before you call the function again rather than check it on entry to the subsequent call) if that will make a difference.
And, with all things, don't optimise unless it's a problem. I'd go for clarity first.
I like the variant 1 better...
It is much easier to read then variant 2. Here you have to understand 3 negations and chain them all together with and. I know its not "hard", but it takes much longer then glancing on variant 1
My vote is for option #1 as well. It looks clearer to me.
I was wondering if there is a performance difference when using ifs in C#, and they are nested or not. Here's an example:
if(hello == true) {
if(index == 34) {
DoSomething();
}
}
Is this faster or slower than this:
if(hello == true && index == 34) {
DoSomething();
}
Any ideas?
Probably the compiler is smart enough to generate the same, or very similar code, for both versions. Unless performance is really a critical factor for your application, I would automatically choose the second version, for the sake of code readability.
Even better would be
if(SomethingShouldBeDone()) {
DoSomething();
}
...meanwhile in another part of the city...
private bool SomethingShouldBeDone()
{
return this.hello == true && this.index == 34;
}
In 99% of real-life situations this will have little or no performance impact, and provided you name things meaningfully it will be much easier to read, understand and (therefore) maintain.
Use whichever is most readable and still correct (sometimes juggling around boolean expressions will get you different behavior - especially if short-circuiting is involved). The execution time will be the same (or too close to matter).
Just for the record, sometimes I find nesting to be more readable (if the expression turns out to be too long or to have too many components) and sometimes I find it to be less readable (as in your short example).
Any modern compiler, and by that I mean anything built in the past 20 years, will compile these to the same code.
As to which you should use then it depends whichever is more readable and logical in the context of the project). Generally I would go for the second myself, but that would vary.
A strong point worth consideration though arises from maintenance. One of the more common bugs I have hunted down is a dangling if/else in the middle of a block of nested ifs. This arises if you have a complex series of if else conditions which has been amended by different programmers over a period - often several years. For example using pseudo-code for a simple case:
IF condition_a
IF condition_b
Do something
ELSE
Do something
END IF
ELSE
IF condition_b
Do something
END IF
END IF
you'll notice for the combination !condition_a && !condition_b the code will fall through the conditions doing nothing. This is quite easy to spot for just the pair of conditions, but can get very easy to miss very quickly once you have 3, 4 or more if/else conditions to check. What commonly happens is the nested structure is correct when first coded, but becomes incorrect (in terms of the business outputs) at some later point because the maintenance programmers will not understand or allow for the full range of options.
It's therefore generally more robust, over time, to code using combined conditions in the if structure adopting the flatest feasible structure and keep nesting to a minimum, hence with your example as there's no logical reason not to combine the two conditions into a single statement then you should do so
I can't see that there will be any great performance difference with either, but I do think that option two is MUCH more readable.
I don't believe there is any performance difference you might be experiencing between the two implementation..
Anyway, I go for for the latter implementation because it is more readable.
Depends on the compiler. The difference will be more apparent when you have code after the close of the nested if, but before the close of the outer.
I've wondered about this often myself. However, it seems there really is no difference (or not much to speak of) between the options. Readability-wise, the second option is more readable and so I usually choose that one unless I anticipate having to code specifically for each condition for some reason.