我有20 x element.selector 相同(100px
)高度,我需要得到它们的高度(100px
,而不是2000px
)。< / p>
什么更快/更有效率?
$(".selector").height()
或
$(".selector").eq(0).height()
答案 0 :(得分:1)
run 1 run 2 run 3 run 4
with_eq: 1956.769ms 1875.220ms 1930.814ms 1895.359ms
no_eq: 1851.168ms 1861.596ms 1804.347ms 1829.207ms
似乎不使用 eq(0)
的速度稍快一点。很明显,因为你在jquery对象上保存了另一个函数调用。不打电话总是比打电话快。
这是我的测试用例:
// noprotect
console.time('with_eq');
for (var i = 0; i<40000; i++) {
$(".foo").eq(0).height();
}
console.timeEnd('with_eq');
console.time('no_eq');
for (var i = 0; i<40000; i++) {
$(".foo").height();
}
console.timeEnd('no_eq');
.foo { height:100px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
<div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>