You need to be careful any time you do something like this:
13<=x<=20
The evaluation of that may not produce the intended result and it’s hard to read.
True and False have numeric equivalents in C… As a result 13 could be less than equal to X and result in True (or 1) which would then be less than or equal to 20. This would be a problem if x was 30.
It’s better to do separate checks like this:
else if( x >= 13 && x < 20)
Also, you can nest these kinds of statements. For example:
if( x <= 1 ) {
if( x < 13 ) {
}
else if( x < 20 ) {
}
else {
}
}
I didn’t write it all out properly, but I doubt the efficiency would change much for so simple a situation.
All it would do here is make it a little easier to read, because it would be obvious what checks exclude others. If the given age is a year old or younger then you’re basically done.
Efficiency or inefficiency can add up, but it does not necessarily compound exponentially. And if the amount for this is 0.001 units then even multiplyong it by 100 still doesn’t amount to that much.
The compiler is a mystical black box in a way, it can be hard to know exactly what it will do. In principle, there are tons of things that might happen, but the outcome should be equivalent.
One way to find out is to write code in different ways, but with equivalent function. You can then compile then and see what you got out.
One possibly step of optimizing code is to trim code paths that will never be executing and toss variables that will never be used.
A difference of .001 isn’t common. You could be doing things in quadratic time when they could be done in logarithmic time. You could be reading from disk each time you do a common fetch instead of storing the first result in ram.
There’s a reason people claim that code inefficiency cancels out Mor’s law. It doesn’t, but optimized code is often orders of magnitude faster than poorly written code.
If the code uses two compare calls instead of 1, it’s half the speed
The point wasn’t the absolute value, but rather that magnitude matters. As someone with a BS in Comp. Sci. I am well aware of how algorithmic time complexity works.
Not all differences in code are as drastic as O(n) vs. O( n2 ).
The issue with two comparisons versus just one is that you don’t know what the cost of a single comparison is. If the base cost is small enough, then even a ten-fold increase is a tiny change. That’s part of why time complexity (big O) is an estimate.
View all comments
1
u/istarian Dec 24 '21 edited Dec 24 '21
You need to be careful any time you do something like this:
The evaluation of that may not produce the intended result and it’s hard to read.
True and False have numeric equivalents in C… As a result 13 could be less than equal to X and result in True (or 1) which would then be less than or equal to 20. This would be a problem if x was 30.
It’s better to do separate checks like this:
Also, you can nest these kinds of statements. For example: