Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / jQuery - Is there a performance difference between height() and .css({'height'})

Setting height this way:

$('element').height(1000);

And this way:

$('element').css({'height': '1000px'});

Is there any kind of performance difference between these two?

Does it also have any bearing on the performance of CSS3 transitions?

like image 736
shrewdbeans Avatar asked Oct 21 '22 06:10

shrewdbeans


1 Answers

Read the Source, Luke.

jQuery.prototype.height:

//snipped to end:
return value === undefined ?
    // Get width or height on the element, requesting but not forcing parseFloat
    jQuery.css( elem, type, extra ) :

    // Set width or height on the element
    jQuery.style( elem, type, value, extra );

jQuery.prototype.css:

return value !== undefined ?
    jQuery.style( elem, name, value ) :
    jQuery.css( elem, name );

The difference between the two is what's done before going over the matched elements, and that extra parameter that's passed in .height. What could rationally cause a big slowdown? I've no real idea. Maybe it has to do with optimizations a js engine can do in one, but not the other. More likely than not, the perf test is bad (testing these things correctly is very hard).

However, the performance of these methods shouldn't be your top concern. If it truly was a problem, you could attempt to solve it by trying both methods, and seeing which makes a considerable improvement. As the proverb goes: "Premature optimization is the root of all evil".

Elaborating, if you do notice something's being slow in your program, and you track it down to a call to .height, then you can see if there's a performance difference by switching to .css.

like image 90
Zirak Avatar answered Oct 27 '22 10:10

Zirak