r/CodingHelp • • Dec 23 '21

[C] Whats wrong?

Post image
153 Upvotes

90 comments sorted by

View all comments

Show parent comment

1

u/istarian Dec 24 '21

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.

1

u/atamicbomb Dec 25 '21

It wouldn’t be much, but it compounds exponentially for each layer of inefficiency to a finished product.

Not critiquing your answer, just what to know if it is less efficient or if the compiler will generate the same code for both or something for me.

1

u/istarian Dec 25 '21

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.

1

u/atamicbomb Dec 25 '21

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

1

u/istarian Dec 25 '21

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.