$ .each () 대 for () 루프-및 성능
이것들은 주로 내가 궁금해했던 것입니다. 누군가가 나에게 조금 더 통찰력을 줄 수있을 것입니다. 지금까지 내가 알아 낸 것을 공유하겠습니다!
내가 궁금해했던 첫 번째 것은 ... 사용할 좋은 점이나 이유가 있습니까?
$('element').each(function (i, el) { });
-대-
$.each($('element'), function (i, el) { });
jQuery 문서를 보면 어떤 운율이나 이유도 볼 수 없습니다. (아마도 인스턴스 나 다른 것에 대해 할 수있는 추가 작업을 알고있을 수 있습니다.
하지만 더 중요한 것은 여기서 속도에 관심이 있습니다
// As opposed to $.each() looping through a jQuery object
// -- 8x faster
for (var i = 0, $('.whatever').length; i < len; i++) {
$('.whatever')[i] // do stuff
}
이 체크 아웃하는 경우 여기 jsFiddle DEMO를 , 당신은 속도의 차이는 그들 중 하나와 기본적으로 동일하다 볼 수 있습니다,하지만 난해야처럼 더 중요한 것은 느낌 항상 사용하는 for()
루프를 ...
나는 단지 단위 테스트 (5 개의 다른 시나리오 함수 각각을 50,000 번 반복)하고, 단순히 목록 항목을 반복하고 data-newAttr
, 아무것도 설정 하지 않았습니다.
질문 :: 내 가장 큰 질문은 객체를 반복하는 동안 항상 for 루프를 사용 하지 않는 이유입니다 . $ .each () 사용에 대한 요점이 있습니까? jQuery 객체를 통과 할 때에도 항상 for () 루프를 사용합니까?
Function type: Execution Time:
_testArea.each() + $(this) 1947 <-- using $(this) slows it down tremendously
$.each() + $(this) 1940
_testArea.each() + el(plain JS) 458 <-- using the Element speeds things up
$.each() + el(plain JS) 452
for() loop + plainJS[0] iteration 236 <-- over 8x faster
내 2 센트. :)
루프로는 .each()
할 수없는 일을 할 수있는 한 가지는 chaining 입니다.for
$('.rows').each(function(i, el) {
// do something with ALL the rows
}).filter('.even').each(function(i, el) {
// do something with the even rows
});
나는 당신의 주위에 재생 JSFiddle 체인 당신이 일치하는 요소의 원래 집합의 부분 집합을 통해 루프이 경우 성능에 영향을 미칠 것입니다 방법을 볼 수 있습니다.
결과는 그다지 예상치 못한 것은 아니지만, end()
적은 수의 요소와 많은 루프의 조합으로 인해 여기 에서 오버 헤드 가 과장 되었다고 생각합니다 . 그 외에는 일반 JS 루프가 여전히 약간 더 빠르지 만 추가 된 가독성 .each()
(및 연결)에 영향 을 미치는지 여부 는 논쟁의 여지가 있습니다.
한 가지는 .each()
자동 로컬 범위 지정 (모든 객체에 대해 익명 함수를 호출하기 때문에)입니다. 즉, 더 많은 익명 함수 / 클로저 / 이벤트 핸들러 / 모든 반복을 생성 할 때마다 그럴 필요가 없습니다. 변수를 공유하는 핸들러에 대해 걱정하십시오. 즉, JavaScript는 로컬 범위와 관련하여 다른 언어처럼 작동하지 않지만 어디서나 변수를 선언 할 수 있기 때문에 때때로 속일 수 있습니다.
즉, 이것은 잘못된 것입니다.
var idx,el;
for (idx = 0; idx <someObjectArray.length; idx++){
el = someObjectArray[idx]
el.someEventHandler(function(){
alert( "this is element " + idx);
});
}
이러한 객체 중 하나가이 루프 이후에 "someEvent"를 호출 할 때마다 (이것이 구성되어 있다는 점에 유의하십시오) 경고는 항상에 마지막으로 할당 된 내용을 말하며 idx
(호출 된 시간 기준) someObjectArray.length
;
적절한 인덱스를 저장하려면 로컬 범위를 선언하고 변수를 만든 다음 해당 변수에 할당하여 사용해야합니다.
var idx,el;
for (idx = 0; idx <someObjectArray.length; idx++){
el = someObjectArray[idx];
(function(){
var localidx = idx;
el.someEventHandler(function(){
alert( "this is element " + localidx);
});
})();
}
보시다시피, 그것은 지옥만큼 추악하지만 작동합니다. 각 이벤트 핸들러는localidx
이제 그것을 비교하십시오 .each()
$(someObjectArray).each(function (idx, el) {
el.someEventHandler(function(){
alert( "this is element " + idx);
});
});
훨씬 간단하지 않습니까?
jQuery.each 대 for 루프
jQuery.each 장점 :
- jQuery 코드 (체인 및 스타일)에 잘 맞습니다.
- 범위에 대해 걱정할 필요가 없습니다 (반복자 및 객체에 대한 참조는 영구적입니다).
- 범용으로 사용할 수 있습니다 (모든 종류의 객체 및 객체 키 반복).
for-loop의 장점 :
- High performance (for games/animations/large datasets).
- Full control over iterator (skip items, splice items from list, etc).
- The for-loop will always work, for there is no dependency on jQuery.
- Same familiar syntax as most other similar languages.
Example code
This is example code of how I prefer to iterate over a list.
var list = ['a', 'b', 'c', 'd', 'e', 'f'];
jQuery.each:
$.each(list, function(i, v)
{
// code...
});
For-loop without closure:
for(var i=0,v,n=list.length;i<n;i+=1)
{
v = list[i];
// code...
}
For-loop with closure:
for(var i=0,n=list.length;i<n;i+=1)
{
(function(i, v)
{
// code...
})(i, list[i]);
}
Note: I suggest you just use the standard for-loop, and only use a closure when necessary. However, when your code looks more like jQuery than Javascript anyway, it could be easier to just use $.each
. In case of performance issues, you could always look into it afterwards.
I ran some simple performance test while ago http://jsperf.com/forloops3. Seems that sticking to plain, old for loop
(where it's possible) is the way to go :)
When I went to your link here are two numbers I got:
$.each() + el(plain JS) 401
for() loop + plainJS[0] iteration 377
If the difference is that small, then go with the one that is most readable, but, if you have very high time requirements, then you may just need to go with what ends up being the fastest.
I would suggest you write your program to use three different methods, the two above, and then use the foreach found in newer versions of javascript, and for those browsers that don't support it you can add it as a prototype.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
You know what your requirements are, and what your program will do, so just write your own tests and ensure it meets the requirements across at the browsers you will be supporting.
For your first question, I would go with $('element').each
as it is much easier to read, but that just my opinion.
Actually there is a big difference between $.each() and $().each().
They do slightly different things depending on what you're passing in.
http://api.jquery.com/each/ vs http://api.jquery.com/jquery.each/
jquery.each is a generic iterator, where $().each() is specific to a jquery collection.
Also see: http://jsperf.com/each-vs-each-vs-for-in/9
참고URL : https://stackoverflow.com/questions/11887450/each-vs-for-loop-and-performance
'IT박스' 카테고리의 다른 글
GNU는 공백이있는 파일 이름을 처리 할 수 있습니까? (0) | 2020.11.12 |
---|---|
std :: vector 및 std :: array에 대한 C ++ initializer_list 동작이 다른 이유는 무엇입니까? (0) | 2020.11.12 |
Eclipse : 리소스가 Java 프로젝트의 빌드 경로에 없습니다. (0) | 2020.11.11 |
Mono로 .net 앱을 실행할 수 없음-mscorlib.dll을 찾을 수 없음 (버전 불일치?) (0) | 2020.11.11 |
javascript, isArray와 같은 isObject 함수가 있습니까? (0) | 2020.11.11 |