For code review technique training, I have to cover various topics. One of them is premature optimization. I found 3 traits of it as:
- It's generally evil; causing inverse effects.
- It's an unnecessary pain, causing no gain.
- It demands lot of effort to achieve little benefits
Is there any other trait which am I missing ? Also, to illustrate them, I usually get a good examples for only 1st scenario. Can someone suggest any solid example for 2nd and 3rd scenario also ?
Example for 1st scenario:
Using char instead of int for smaller loops to save bytes!
for(char c = 0; c < 20; c++) {} //Evil: Accessing 'char' costlier than 'int'
[Note: I am not worried about the fact that compilers usually itself takes care of premature stuff. This training is meant just for illustration.]
This question is not about, "What optimizations are premature?"
i++
vs.++i
, but will call it "good design" to throw in hash tables everywhere, back pointers, and deep notifications. IMHO those are both premature optimization.unsigned char
rather than anint
is often a good idea in the particular case where one is coding for an 8-bit embedded processor. On an 8051,do{...} while(--someByte)
will compile the loop branch toDJNZ someByte,branchTarget
(three bytes; two cycles). Using anint
would yield something more likemov a,someInt+1 / add a,#255 / mov someInt+1,a / mov a,someInt / adc a,#255 / mov someInt,a / orl a,someInt+1 / jnz loopTarget
. About nine cycles. Not exactly a "small" optimization.