2017-11-11 11 views
1

나는이 같았다 코드의 조각을했다 :비 사소한 고토 사용 (컴파일러 이길 수)

f += .001f; //Only needs to be executed when loop executes at least one iteration, but does no harm if incremented without entering the loop 
while(anIndex < aVaryingBoundary) { 
    if(something) { 
     //code 
     continue; 
    } 
    //more code 
} 

이 코드보다 효율적으로 발견하는 유일한 방법 (F의 불필요한 증가를 제거하여) 고토를 사용했다.

if(anIndex < aVaryingBoundary) { 
    f += .001f; 

loop: 
    if(something) { 
     //code 
     if(anIndex < aVaryingBoundary) { 
      goto loop; 
     } 
     else { 
      goto loop_end; 
     } 
    } 
    //more code 
    if(anIndex < aVaryingBoundary) { 
      goto loop; 
    } 
} 
loop_end: 

단순한 최적화이지만 컴파일러가이를 쉽게 감지 할 수 있다고 생각하지 않습니다. 컴파일러가 수행하는 것이 그리 평범한가요?

+0

왜 사용하는'goto' - 멀리 방주 –

+0

대신의'if' 내부의'goto', 왜 그냥 추가 루프 갔던? –

+0

어떻게 최적화합니까? – melpomene

답변

3

는 단지

if (anIndex < aVaryingBoundary) { 
    f += .001f; 
    do { 
     if(something) { 
      //code 
      continue; 
     } 
     //more code 
    } while(anIndex < aVaryingBoundary); 
} 

아닌가?

+0

또는 if (something) {/ * code * /} else {/ * more code * /}'를 루프 본문으로 사용하십시오. 계속 필요하지 않습니다. –

+0

@JonathanLeffler 나는 그것이 실제로 필요할 때부터 우연히 거기에서 계속 나왔다. –

2

이렇게하면 goto이 필요하지 않으므로 컴파일러에서 최적화 할 수 있습니다.

if(anIndex < aVaryingBoundary) { 
    f += .001f; 
    // Tag loop: 
    while (true) { 
     if(something) { 
      //code 
      if(anIndex < aVaryingBoundary) { 
       continue; 
      } 
      else { 
       break; 
      } 
     } 
     //more code 
     if(anIndex < aVaryingBoundary) { 
      continue; 
     } 
     break; 
    } 
} 
// Tag loop_end: 

주요 논리 구조는 변경되지 않습니다,하지만 더 이상 goto의가 없습니다.

+0

계속 및 중단 대신 부울 변수 일 수 있습니다. –

+0

@EdHeal 더 많은 변경이 필요합니다. – iBug

+1

그래서 뭐 - 코드를 더 읽기 좋게 만들 것입니다. –

0
if(anIndex < aVaryingBoundary) { 
    f += .001f; 

    while(anIndex < aVaryingBoundary) { 
     if(something) { 
      //code 
      if(anIndex < aVaryingBoundary) continue; 
      else break; 
     } 
     //more code 
    } 
}