performance - Conditional Branching Efficiency -
we part of discussion on how make codes more efficient , on topic of branching on if-else
, came up.
consider following piece of code:
if (a==1) { //... tasks } else if (a==2) { //... tasks } ... } else if (a==9) { //... tasks }
the discussion proved upper code lesser efficient 1 below because of number of comparisons must made towards lower half of code.
consider alternative:
if (a<=4) { if (a==1) { //... tasks } else if (a==2) { //... tasks } ... } else { if (a==5) { //... tasks } else if (a==6) { //... tasks } ... }
in above case, checking a=5,6,7, or 8
takes lesser number of comparisons , more efficient. i've never come across code use logic. codes use switch
statement or normal if
condition mentioned in former snippet. latter code more efficient or take same amount of time?
edit: above example. general idea distinguish disjoint sets of conditions pool of conditions , apply conditions based on reason of disjoint.
yes, second code more efficient in average case.
there 3 reasons why don't see such code:
the improvement relatively slight. amount varies depending on cpu, save single digit count of cpu cycles.
the impact on code readability severe.
the amount of code needs optimization less 1 percent of code that's written.
you see, vast majority of code it's not worth it.
also note second code may slower first one: if a == 1
vast majority of cases, second code needlessly adds second comparison critical path. never optimize without understanding critical path.
Comments
Post a Comment