Array Initialization

JavaScript performance comparison

Test case created by Sebastian

Info

How to initialize an array with a default value quickly.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var length = 5678;
    var initialValue = 23;
   
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
For-Loop
var a = new Array(length);

for (var i = 0; i < length; i++){
 a[i] = initialValue;
}
pending…
for-loop backwards
var a = new Array(length);

for (var i = length-1; i >= 0; ){
 a[i--] = initialValue;
}
pending…
Exponential duplication
var a = [initialValue];

while (a.length < length){
   a = a.concat(a);
}

a.length = length;
pending…
Exponential duplication with cache
if (!window.cache){
 window.cache = {}
}
var a;
if (window.cache[initialValue]){
  a = window.cache[initialValue];
} else {
  a = [initialValue];
}

while (a.length < length){
   a = a.concat(a);
}
window.cache[initialValue] = a;
a = a.slice(0, length);
pending…
Exponential duplication with concat
if (!window.cache2){
 window.cache2 = {}
}
var a;
if (window.cache2[initialValue]){
  a = window.cache2[initialValue];
} else {
  a = [initialValue];
}

while (a.length < length){
   a = a.concat(a);
}
window.cache2[initialValue] = a;
a = a.concat()
a.length = length
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:

0 comments

Add a comment