find element in obj vs array
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
var obj = {},
arr = [],
count = 0;
for (var i = 0; i < 1000; i++) {
arr.push(i);
obj[i] = 1;
}
function in_array(needle, haystack) {
for (var i = 0, maxi = haystack.length; i < maxi; ++i) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}
function include(needle, haystack) {
return (haystack.indexOf(needle) != -1);
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
find in array (1) |
|
pending… |
find in array (5) |
|
pending… |
find in array (9) |
|
pending… |
find in obj (1) |
|
pending… |
find in obj (5) |
|
pending… |
find in obj (9) |
|
pending… |
indexOf in arr(1) |
|
pending… |
indexOf in arr(5) |
|
pending… |
indexOf in arr(9) |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published
- Revision 2: published
- Revision 3: published
- Revision 4: published by Rob Edgar
- Revision 6: published
2 comments
Chrome 18.0.1025 is actually Chrome Mobile (first non-beta) on a Samsung Galaxy S3
I don't trust this benchmark. I am afraid that the JIT compilers are optimising the calculation by moving the entire computation outside of the loop, thereby defeating the test. The reason I think this is that (a) it's just so fast, and (b) in some cases it seems not to depend on 1 vs 5 vs 9 (and anyway all of those numbers are too small).