简体   繁体   中英

jquery performance variable

few question, i want to know when i should use variable, if the selector will call more than one time, then i should variable that selector?

  1. local or global variable? for example

var $body = $('body');

if i have 100 jquery function, each function need $('body') selector, local 100 time or global one time variable will faster?

  1. if a function like below

    $('.link').on('click', function() { var $this =$(this); $this.addClass('a'); });

the function is finish, only call $this one time, should i need $this ? or just use $(this) ? which one is faster?

  1. variable non-selector

    $('one').addClass('a').removeClass('b').html('abcd'); $('two').addClass('a').removeClass('b').html('abcd');

if i create a variable var job = addClass('a').removeClass('b').html('abcd');

`$('one').job;
$('two').job;`

will it be faster? or useless?

  1. resize function variable, to made a full height div, which one will be faster?

    $('#full-height').css({'height' : ($(window).height() + 'px')}); //without variable
    var vH = $(window).height(); $('#full-height').css({'height' : vH + 'px'}); //with variable
    var vH = $(window).height(); $('#full-height').height(vH + 'px'); //with variable and use height() method

all of above function run inside $(window).on('resize', function() {} , so each time resize the function will run, will the variable code faster?

when i need to variable non-selector?

thanks soooo much

If you use an element multiple times, saving it in a variable (a pointer for an element) will improve performance for sure, because like you said it's a query , jQuery will fetch all the DOM to find the element that you need, so saving the result of a query in a variable will be faster, and it's a good habit.

So using $this instead of $(this) will improve performance too.

*For the Question 3

You can't do job = addClass... because addClass is not a global functions! it's a jQuery object method! so you can use it only with a jQuery object/element $jqObject.addClass...

*Question 4

Like I said if you are using a result of a method multiple times in the same function , you should put it in a variable, but in your example you are using the $(window).height(); only one time, so puting it in variable is useless but it's a good habit for a clean code . and it will not affect performance.

So in simple words: if you are using a result of a method multiple times in the same context, saving it in a variable will improve performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM