.index() vs .each()
JavaScript performance comparison
Preparation code
<div class="container1">
<p>
This is content 1
</p>
<p>
This is content 2
</p>
<p>
This is content 3
</p>
</div>
<div class="container2">
<p>
This is content 1
</p>
<p>
This is content 2
</p>
<p>
This is content 3
</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
$('.container1').children('p').hover(function() {
var index = $(this).index() + 1;
alert(index);
});
$('.container2').children('p').each(function(index, element) {
// use closure to retain index
$(element).hover(function(index) {
return function() {
alert(index);
};
}(index));
});
};
</script>
Preparation code output
This is content 1
This is content 2
This is content 3
This is content 1
This is content 2
This is content 3
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
index |
|
pending… |
each |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments