简体   繁体   English

Javascript / jQuery - height()和.css({'height'})之间是否存在性能差异

[英]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? 它是否也与CSS3过渡的性能有关?

Read the Source, Luke. 阅读来源,卢克。

jQuery.prototype.height : 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 : 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 . 两者之间的差异是在.height匹配元素之前所做的事情,以及传入的extra参数.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. 也许它与js引擎在一个中可以做的优化有关,而与另一个无关。 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 . 如果您确实注意到程序中的某些内容很慢,并且您将其跟踪到.height的调用,那么您可以通过切换到.css来查看是否存在性能差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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