- Home /
< cheaper than <= ?
I had heard a long time ago that using < was computationally faster than <=. The reasoning was that <= was just a shorthand for < and =, which meant that the program would have to perform two comparison checks. Can anyone confirm or deny this?
Answer by Eric5h5 · Sep 05, 2012 at 10:30 PM
<= is not any faster or slower than <. You can confirm this by running a simple benchmark. See the question about this on Stack Overflow.
Thank you Eric. I'd hoped you'd have a final answer on this.
Answer by Owen-Reynolds · Sep 05, 2012 at 07:32 PM
Stuff like `<` vs '`<=` is pretty far down on the list of things to worry about. The usual rules, in order, are:
o Don't optimize early. Always choose to write a readable program over a "fast" one. There's a good chance things will change and your optimized code section will be a pain to update.
o Don't bother with infrequent code sections. Monsters only die once, so no point making "die" run faster. Focus on things that happen every frame.
o Look at the big picture. Does target acquisition need to run every frame? Does every monster have a local copy of common data that could be stored in just one place (bigger programs can't fit into L1 cache, so run slower.) Shouldn't that giant nested-if/switch be turned into an array lookup?
o Don't assume you're smarter than the compiler. It's likely that `if(a<=b) do C; else do D` will get flipped around during compile to `if(a>b) do D; else do C`.
That's good advice. However, I was mostly just asking out of curiosity. I wouldn't be a bit surprised if a program could do a million >= operations in a second, I just wondered if > was faster.
Plus, thinking in terms of > ins$$anonymous$$d of >= is an easy enough way to optimize that it wouldn't turn code unreadable, so knowing the rule had some benefit in my $$anonymous$$d.
Always write for readability first. The example in $$anonymous$$ike's answer of using (a < b+1) rather than (a <= b) is exactly what you should not do. Especially since neither is actually any faster than the other.
Screenhog: there's usually an "obvious" operator for readability. For example, `if(x<200)` looks like an "off left-edge" check (200 is the smallest, true is bad,) while `if(x<=200)` looks more like a "not past right-edge check" where true is good.
Everything Owen says here is deeply, deeply important. It is incredibly valuable advice.
In particular, points 4, 3, 2 and 1 are extremely critical.