array copy
JavaScript performance comparison
Info
Previous tests were also testing fn construction, not just pure array construction. This differs from http://jsperf.com/slice-vs-copy/ in that these are all function invocations, not just inline (which is basically always faster under 10 members).
Pre-allocating the target array length, see http://jsperf.com/pre-allocationg-vs-literal. Note, the length of the array matters greatly, see http://jsperf.com/slice-vs-copy/ in the revisions/notes.
Preparation code
<script>
Benchmark.prototype.setup = function() {
var arr = new Array(1, 2, 3, 4, 5);
function forinclone(arr) {
var key, arr_clone = new Array(arr.length);
for (key in arr) {
arr_clone[key] = arr[key];
}
return arr_clone;
}
function forclone(arr) {
var i, len = arr.length,
arr_clone = new Array(len);
for (i = 0; i < len; i += 1) {
arr_clone[i] = arr[i];
}
return arr_clone;
}
function pushforclone(arr) {
var i, len = arr.length,
arr_clone = [];
for (i = 0; i < len; i += 1) {
arr_clone.push(arr[i]);
}
return arr_clone;
}
function whileclone(arr) {
var len = arr.length,
arr_clone = new Array(len);
while (len--) {
arr_clone[len] = arr[len];
}
return arr_clone;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
for-loop |
|
pending… |
slice |
|
pending… |
concat |
|
pending… |
modified for-loop |
|
pending… |
push in for-loop |
|
pending… |
while-loop |
|
pending… |
push |
|
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 2: published by keville
- Revision 3: published
- Revision 4: published by Paul Grenier
- Revision 5: published
- Revision 6: published
- Revision 7: published by Jonathan Perry
- Revision 9: published
0 comments