Skip to content

Instantly share code, notes, and snippets.

@dcposch
Last active November 30, 2016 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcposch/aac53194fcd7598f0e44cb6169d9bc34 to your computer and use it in GitHub Desktop.
Save dcposch/aac53194fcd7598f0e44cb6169d9bc34 to your computer and use it in GitHub Desktop.
profiling JS array performance

profiling JS array performance

what's the fastest way to make short-lived arrays in Javascript?

i need to make this array very often. variable length, from a couple to a couple thousand. i don't know each length ahead of time. i also want to minimize memory allocations.

options

  1. create a new array each time, use push() to add elements

  2. create a new array each time, use [] and set the length at the end

  3. preallocate one array, use [] and set the length

    this way does the fewest allocations, and also turns out to be the fastest by a factor of ~2

results

yes, i know this is an unscientific microbenchmark.

done on a 2016 12" Macbook running node 6.4.0

$ node .
1000000 iters
499.38034
create and push: 3233.427ms
499.417887
create and set: 2852.723ms
499.49301
reuse and set: 1634.665ms
499.950513
create and push: 3152.367ms
499.235267
create and set: 2844.127ms
499.46329
reuse and set: 1646.972ms
// array performance microbenchmark
var iter = 1e6
console.log(iter + ' iters')
// allocate the array once for test #3
// tests #1 and #2 allocate a new array each time
var arr3 = []
var i
for (var j = 0; j < 2; j++) {
console.time('create and push')
var tot = 0
for (i = 0; i < iter; i++) tot += f1()
console.log(tot / iter)
console.timeEnd('create and push')
console.time('create and set')
tot = 0
for (i = 0; i < iter; i++) tot += f2()
console.log(tot / iter)
console.timeEnd('create and set')
console.time('reuse and set')
tot = 0
for (i = 0; i < iter; i++) tot += f3()
console.log(tot / iter)
console.timeEnd('reuse and set')
}
function f1 () {
var arr = []
var n = (Math.random() * 1000) | 0
for (var i = 0; i < n; i++) arr.push(i)
return arr.length
}
function f2 () {
var arr = []
var n = (Math.random() * 1000) | 0
for (var i = 0; i < n; i++) arr[i] = i
return arr.length
}
function f3 () {
var n = (Math.random() * 1000) | 0
for (var i = 0; i < n; i++) arr3[i] = i
arr3.length = n
return arr3.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment