2

I once declared and initialized a variable with a default value all together. (var a= "default";)
And in a certain IF condition the variable value has to be changed, so i was changing the value of the variable inside IF condition. If (x==y) { a=" newVal" ;}
During a code review i was asked why i am not assigning the default value in ELSE condition. And i was like whut 😑.
So........ Some Programmers be like IF shouldn't exist without ELSE.

Comments
  • 3
    If you had put it in the else, your code is actually more efficient. As the code issues only 1 assignment when it satisfies the if vs 2 when it satisfies the if.
  • 1
    @brettmoan These optimizations are done by compilers. So is it necessary for us to do these kind of optimization?
  • 3
    @arunabhghosal Considering that you can optimise it again by using a ternary then yeah it is.
  • 0
    @brett@brettmoan that makes sense, but how much that would have affected the overall execution.
  • 0
    @arunabhghosal I'm pretty sure the computer would not optimize it. Since the default would be loaded to a register then saved, then it would be taken out and compared. I'm about 50 to 75% sure that compilers would not convert it to an automatic else.
  • 0
    @manisarao on a simple string running in one thread? Insignificant, very insignificant. On a larger object or done frequently (such as multithreaded application or a large liop) very significant.
Add Comment