2

To specify my Question a bit. I know Code should be readable by Humans in the very first place. But I want to know if there are certain tricks which can add up to the performance a bit.

  1. If there is an Event, that i know will be true 80% of the time. Where should i put the Code in the If clause in general?

    if(Event){ 
        //put here the likely to happen? 
    }else{
        //or here?
    }
    

My thought on this: Most modern Processors guess which branch they take and analyse their decisions. But in this case i know which guess would be better. Can i support this in any way?

  1. Should i use Expressions like this: x << 2 whenever i can, or should the compiler do this work for the sake of readability?

  2. Should i generally speaking, use recursive functions, which i find more readable. Or iterative functions which can be more stable. e.g Fibonacci results in a Stack-overflow on relative small inputs when done recursive.
    Whereas an iterative implementation is much more robust.

To sum up: Are there small things i can do to support the real optimisation done by the compiler (gcc in my case)?
Are those examples to consider or should i not think about this at all?

I hope this Question is not too theoretical. Thanks in advance!

sepp2k
  • 363,768
  • 54
  • 674
  • 675
bitflip-at
  • 149
  • 2
  • 14
  • 1
    You can only recurse so many times before you fill up the stack and your application crashes. Those should be used with caution. Also, related question: http://stackoverflow.com/q/30130930/156811 – Havenard Jan 26 '17 at 18:38
  • 3
    Only worry about optimizing if you've identified a specific issue (use a profiler) or via an actual benchmark using actual data. The compiler and CPU are going to be smarter than you the vast majority of the time; the only time you need to worry about it is if you've actually identified a real problem. – Ken White Jan 26 '17 at 18:39
  • @Havenard Thank you! that answered Q1. I did not find this myself... :( Maybe because those are all C++. Sorry did not notice that – bitflip-at Jan 26 '17 at 18:43
  • 1
    Which optimization you have in mind? Memory performance or CPU performance? What architecture? There are so many things the compilers optimize today it's almost impossible to answer such a question in general. Simply write readable code and give the compiler as much information as possible (e.g. use constants, strong types etc.), use high level structures that the compiler can optimize. Most of the times the readability and maintainability of your code is MUCH more important than some tiny performance improvement. Branch prediction on CPUs will do the job probably better than you can. – Sulthan Jan 26 '17 at 18:44

0 Answers0