티스토리 뷰

javascript

Jquery 속도 향상

아르고우스 2015. 10. 29. 18:29


1. for문 대신에 jquery each를 사용 하자

var array = new Array ();
for (var i=0; i<10000; i++) {
    array[i] = 0;
}
 
console.time('native');
var l = array.length;
for (var i=0;i<l; i++) {
    array[i] = i;
}
console.timeEnd('native');
 
console.time('jquery');
$.each (array, function (i) {
    array[i] = i;
});
console.timeEnd('jquery');

결과

native: 45.877ms

jquery: 7.571ms


2. 태그 생성시 클래스 이름보다는 아이디를 중복 되지 않게 만들자

console.time('class');
var list = $('#list');
var items = '<ul>';
 
for (i=0; i<1000; i++) {
    items += '<li class="item' + i + '">item</li>';
}
 
items += '</ul>';
list.html (items);
 
for (i=0; i<1000; i++) {
    var s = $('.item' + i);
}
console.timeEnd('class');
 
console.time('id');
var list = $('#list');
var items = '<ul>';
 
for (i=0; i<1000; i++) {
    items += '<li id="item' + i + '">item</li>';
}
 
items += '</ul>';
list.html (items);
 
for (i=0; i<1000; i++) {
    var s = $('#item' + i);
}
console.timeEnd('id');


class: 20.547ms

id: 12.349ms


3. 반복문에서는 변수에 담아서 활용 하자


$('#item').css ('color', '#123456');
$('#item').html ('hello');
$('#item').css ('background-color', '#ffffff');
 
// you could use this instead
$('#item').css ('color', '#123456').html ('hello').css ('background-color', '#ffffff');
 
// or even
var item = $('#item');
item.css ('color', '#123456');
item.html ('hello');
item.css ('background-color', '#ffffff');
 
 
// as for loops, this is a big no-no
console.time('no cache');
for (var i=0; i<1000; i++) {
    $('#list').append (i);
}
console.timeEnd('no cache');
 
// much better this way
console.time('cache');
var item = $('#list');
 
for (var i=0; i<1000; i++) {
    item.append (i);
}
console.timeEnd('cache');


no cache: 13.644ms

cache: 9.037ms


4. 스트링을 붙일때는 배열을 사용 하여 join을 활용 하라


console.time('concat'); var array; for (var i=0; i<=10000; i++) { array[i] += '<li>'+i+'</li>'; } $('#list').html (array); console.timeEnd('concat'); console.time('join'); var array = []; for (var i=0; i<=10000; i++) { array[i] = '<li>'+i+'</li>'; } $('#list').html (array.join ('')); console.timeEnd('join');

concat: 66.433ms

join: 55.332ms



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함