programing

while 루프 대신 For 루프

kingscode 2021. 1. 14. 22:54
반응형

while 루프 대신 For 루프


jQuery 소스를 읽으면서 다음 코드를 우연히 발견했습니다 ( 여기에서 사용 가능 ).

for (; i < length;) {
    if (callback.apply(object[i++], args) === false) {
        break;
    }
}

for루프 대신 여기에 루프가 사용되는 이유는 무엇 while입니까?


나는 나쁜 코딩 스타일을 선호하는 사람에게 투표합니다. 이것이 for루프와 i++배열 첨자 내부에 배치되는 것에 대해 볼 수있는 유일한 설명 입니다. 나는 이것이 더 나을 것이라고 생각한다.

while (i < length && callback.apply(object[i], args)) {
    i++;
}

또는 ===원래 예제 연산자에 가치 가 있다고 생각 되면 다음을 수행하십시오.

while (i < length && callback.apply(object[i], args) !== false) {
    i++;
}

이를 수행하는 또 다른 가능한 이유는 성능 최적화 때문일 수 있습니다. 내가 종합 한이 빠른 벤치 마크 는 그 이론을 반증하는 것처럼 보이지만. Windows에서 while위의 for루프는 Chrome 의 원래 루프 보다 20 % 빠르며 IE와 Firefox에서는 두 루프가 모두 동일하게 수행됩니다. OS X에서 for루프는 파이어 폭스에서 10 %의 이점을 가지고 있으며 크롬에서는 둘 사이에 차이가 없으며 사파리는 while루프를 6 % 선호합니다 .

따라서 성능 측면에서 볼 때 세척입니다. 시장 점유율로 판단하면 Mac에서 Firefox를 최적화하기 전에 Windows에서 Chrome을 최적화하고 싶을 것입니다.이 경우 while루프가 선호됩니다.

성능 최적화가이 코드에 영향을 미칠 것 같지는 않습니다. 그리고 나는 그것이 코드 검토 과정을 지나게 만드는 열악한 코딩 스타일의 예일 뿐이라는 원래 이론으로 돌아갑니다.


아마도 for (x in obj)루프 에서 "리팩토링"되었기 때문일 것입니다 : http://james.padolsey.com/jquery/#v=1.3.2&fn=jQuery.each


여기 에이 기이함을 도입 한 커밋이 있습니다.

커밋 메시지 :

jquery 코어 : $.each$.curCSS.

차이에서 캡처 :

-        for ( var i = 0, length = object.length; i < length; i++ )
-          if ( callback.apply( object[ i ], args ) === false )
+        for ( ; i < length; )
+          if ( callback.apply( object[ i++ ], args ) === false )

저자가 단순히을 변경할 수있는 기회를 놓친 것으로 생각된다 for로를 while.


첫째, for루프를 통해 루프 를 사용하는 데 길이 비용이 들지 while않지만 루프를 통해 추가 기능을 얻을 수 for있으므로 일부 코더는 항상 다음을 사용합니다 for.

for(;<condition>;){}
while(<condition>){}

즉, 여기서의 목적은 주변 코드와의 일관성 때문일 수 있습니다.

예를 들어, 다음은 원본 코드의 일부입니다. 보시다시피이 코드에서 "for"루프 모드를 유지하여 전체 시간을 생각할 수 있으므로 보다 일관성있는 느낌이 듭니다 .

if (args) {
    if (isObj) {
        for (name in object) {
            if (callback.apply(object[name], args) === false) {
                break;
            }
        }
    } else {
        for (; i < length;) {
            if (callback.apply(object[i++], args) === false) {
                break;
            }
        }
    }
}

Compare this to replacing the second loop with a while. When you read this code, you have to switch from the "for" loop mode of thinking to the "while" loop mode of thinking. Now I don't know about you, but I find it slightly faster for my eyes to switch between the loop conditions above as opposed to the loop conditions below. This is because in the above case I can just concentrate on the conditions, whereas in the below case my eyes are drawn to reread the while and the for each time because they are different:

if (args) {
    if (isObj) {
        for (name in object) {
            if (callback.apply(object[name], args) === false) {
                break;
            }
        }
    } else {
        while (i < length) {
            if (callback.apply(object[i++], args) === false) {
                break;
            }
        }
    }
}

I've found that things like this occur when I rewrite things or if multiple people touch a piece of code. Can't see any particular reason for it.

I hope i gets initialized properly above this block.


The shortest and most honest answer is pretty short "just because". There is absolutely no practical reason to do it, we don't gain any profit from such 2-smiles loop.

As for aforementioned reasons, such as:

  • refactoring - which is most possible, but nevertheless this is not an excuse.
  • minification considerations - which is less, less possible.
  • psychological/readability/code supporting issues - I very dubious that somebody write such code keeping in mind that a user can be confused for some code constructions and loose concentration;

well, as for these reasons - all of them definitely worth mentioning, but, to be honest, jquery code style is, well, not ideal. Sometimes there are reasons why it is so, some times, it's just a matter of fact.

Production code is not always the most beautiful code. Reading production-ready, hardcore code on any language is always for good, but is not 100% about code style. Say, vim is beautiful, very powerful software, but (as for me) some purist can be surprised with it source code. Though loops stuff is ok ))))


So t will run at least once, because if you use a while loop if the logic is false it wont run. For lopp even if it is false it will run atleast once.

ReferenceURL : https://stackoverflow.com/questions/7168995/for-loop-instead-of-while-loop

반응형