Nice programing

'$ (this)'비용은 얼마입니까?

nicepro 2020. 12. 30. 20:24
반응형

'$ (this)'비용은 얼마입니까?


여기 사람들은 종종 다음 코드와 같이 요소 jQuery에서 생성 된 객체 를 캐시하도록 제안 DOM합니다.

$('#container input').each(function() {
    $(this).addClass('fooClass');
    $(this).attr('data-bar', "bar");
    $(this).css('background-color', 'red');
});
  • jQuery 객체를 캐싱하면 실제로 코드의 성능이 향상됩니까?
  • DOM 요소를 jQuery 생성자에 전달할 때 "뒤에서"어떤 일이 발생합니까?

jQuery 태그 정보 에서이 경고가 나타납니다.

jQuery 함수 $ ()는 비싸다. 반복적으로 호출하는 것은 매우 비효율적입니다.

음 ... 정규식으로 구문 분석되어 그들이 무엇인지 알아내는 문자열 선택자에만 해당됩니다.

quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/

그런 다음 문자열이 선택기 (제외 id) 인 경우 jQuery는 DOM을 탐색하여 값 비싼 find함수 와 일치하는 항목을 찾습니다 .

} else if ( !context || context.jquery ) {
    return ( context || rootjQuery ).find( selector );
}

예, 비싸지 만 선택자에게만 해당됩니다!

를 전달하면 DOMElementjQuery가 수행하는 유일한 작업은 DOMElement 매개 변수를 새로 생성 된 jQuery 객체의 컨텍스트로 저장하고 컨텍스트의 길이를 1로 설정하는 것입니다.

// Handle $(DOMElement)
if ( selector.nodeType ) {
    this.context = this[0] = selector; // Selector here is a DOMElement
    this.length = 1;
    return this;
}

내가 그랬어 jsPerf 몇 가지 테스트를 , 나는 참으로 jQuery 오브젝트를 캐싱하는 것은 단지 약간의 영향을 미친다는 것을 발견 :

아래에 설명 된 막대 차트

Chrome에서는 7 % 만 느립니다. (IE에서는 12 %가 조금 더 중요합니다.)


두 번째 질문에 답하려면 출처를 확인 하세요.

// Handle $(DOMElement)
if ( selector.nodeType ) {
    this.context = this[0] = selector;
    this.length = 1;
    return this;
}

성능 차이와 관련하여 둘을 직접 비교하려는 경우 DOM 선택 및 직접 관련되지 않은 기타 메서드와 같이 결과를 왜곡 할 수있는 추가 코드를 제거하는 것이 좋습니다.

http://jsperf.com/this-cost/2

여기에 이미지 설명 입력

보다 실제적인 환경에서는 테스트 결과에 따라 상대적인 차이가 작습니다.

명심해야 할 또 다른 사항은 jQuery 객체를 생성 할 때마다 메모리를 할당해야한다는 것입니다. 이로 인해 가비지 수집기가 수행해야하는 작업이 추가됩니다.

그래서 사람들이 캐싱을 제안하는 이유는 다소 원칙적인 관점에서 비롯된 것 같습니다. 일반적으로 눈에 띄는 영향을 미치지는 않지만 궁극적으로 쉽게 피할 수있는 약간의 오버 헤드가 필요한 추가 작업이 수행되고 있습니다.


여기에있는 모든 런타임 성능 테스트에서 놓치는 한 가지 주요 고려 사항은 다음과 같습니다.

네트워크 대역폭.

$(this)지역 변수에 캐싱 하면 일반적으로 특히 축소 될 때 스크립트의 크기 this가 줄어 듭니다 (4 자에서 줄일 수 없기 때문 ).

중히 여기다:

function hello(text) {
    $(this).attr();
    $(this).css();
    $(this).data();
    $(this).click();
    $(this).mouseover();
    $(this).mouseleave();
    $(this).html(text);
}
hello('Hello world');

클로저 컴파일러의 축소 된 출력은

function hello(a){$(this).attr();$(this).css();$(this).data();$(this).click();$(this).mouseover();$(this).mouseleave();$(this).html(a)}hello("Hello world");

이렇게하면 39 바이트 (20 %)가 절약됩니다. 이제 다음을 고려하십시오.

function hello(name) {
    var $this = $(this);
    $this.attr();
    $this.css();
    $this.data();
    $this.click();
    $this.mouseover();
    $this.mouseleave();
    $this.html(name);
}
hello('Hello world');

축소 된 출력은 다음과 같습니다.

function hello(b){var a=$(this);a.attr();a.css();a.data();a.click();a.mouseover();a.mouseleave();a.html(b)}hello("Hello world");

This saves 74 bytes (37%), nearly doubling our byte savings. Obviously, real world savings in large scripts will be lower, but you still stand to gain significant reductions in the size of your script by caching.

Really, there's only an upside to caching $(this). You get miniscule but measurable runtime performance gains. More importantly, you can reduce the number of bytes that travel over the wire, and that directly translates to more dollars because faster page loads equal more sales.

When you look at it that way, you could actually say there's a quantifiable dollar cost to repeating $(this) and not caching it.

ReferenceURL : https://stackoverflow.com/questions/10433014/what-is-the-cost-of-this

반응형