[컴] Does "if" statement inside the loop is better ?

 

which one is better?

for speed optimization, the first code is better than the second one. I've run the program several times. Every running program, time differences were different, but in most cases, the second one is slower than first one. (test source code )

 

 

// first code
result += 1;
for(i=1 ; i<24200000 ; i++){
result += i;
}

 


// second code
int result = 1;

for(int i=0 ; i<24200000 ; i++){
if(i == 0)
{
result += 1;
}
else
{
result += i;
}
}

However, Which is better for the readability or flexibility ?


In my opinion, the second one is better, because it's easy to fix for every cases, and understand how loop works. for example, see the below code. At the code, it's hard to pick out the 'if' statement from the loop. It might be impossible.(There is way to seperate the loop into two loop which one ends before 5 and another starts from the 5.)


int result = 1;

for(int i=0 ; i<24200000 ; i++){
if(i == 5)
{
result += 1;
}
else
{
result += i;
}
}

 


Thus, I think, in most cases, loops are too short to feel the time differences, so it's a good habit to use "second code" than "first code".


 


Please comment on this post 윙크


 


See Also



  1. http://blogs.sas.com/content/iml/2012/02/13/avoid-unnecessary-if-then-statements-in-loops/

댓글 없음:

댓글 쓰기