简体   繁体   中英

Does else cost anything CPU cycles wise?

I have 2 examples:

if (i mod [number] == 0)
      do thing;
else 
      do other thing

and

if (i mod [number] != 0)
       do other thing;
else
       do thing

Are these 2 examples equal CPU cycles wise?

In C you don't write CPU instructions. You write instructions for an abstract C machine. The compiler then transforms your C code into CPU code and it has the freedom to generate any CPU code as long as it keeps the observable behavior of your C program. Since both code snippets are equivalent, both can generate the same assembly code. Don't invert if condition for the sake of performance because it's futile.

A real optimization you can do here is use the [[likely] hint to the compiler. Most compilers have their own C non-standard equivalent. Be aware that this optimization doesn't "save cycles" in the way you think about it. Rather it can help with pipeline branch prediction in certain pattern usage scenarios. Optimization is a very deep and interesting field if you want to go that rabbit hole. It's not as simple as it might appear. Also if this is not hot code any optimization here will have practically no effect. So always first profile profile profile.

First write clean clear code. Then profile and if you find a problem then go in and try optimizations based on what the profiling showed. Don't do premature optimizations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM