Skip to content

Instantly share code, notes, and snippets.

@j-v
Created May 12, 2020 03:44
Show Gist options
  • Save j-v/e775a2e7c038a3b0cd33843fc277bf04 to your computer and use it in GitHub Desktop.
Save j-v/e775a2e7c038a3b0cd33843fc277bf04 to your computer and use it in GitHub Desktop.
array operations performance
var arrsize=100000
// time cost for array constructing
var i = 0
var ar = [] // literal notation
var arr = new Array(arrsize) // new length defined
i = 0
console.time("Literal notation with assigning directly")
while(i<arrsize){
ar[i] = i
i++
}
console.timeEnd("Literal notation with assigning directly")
i = 0
ar = []
console.time("Literal notation with push()")
while(i<arrsize){
ar.push(i)
i++
}
console.timeEnd("Literal notation with push()")
ar = []
console.time("Literal notation with unshift()")
while(i>=0){
ar.unshift(i)
i--
}
console.timeEnd("Literal notation with unshift()")
i = 0
ar = []
console.time("Literal notation with push()")
while(i<arrsize){
ar.push(i)
i++
}
console.timeEnd("Literal notation with push()")
console.time("Literal notation with shift()")
while(i>=0){
ar.shift()
i--
}
console.timeEnd("Literal notation with shift()")
i = 0
ar = []
ar.length = arrsize
console.time("Literal notation with declaring length first")
while(i<arrsize){
ar[i] = i
i++
}
console.timeEnd("Literal notation with declaring length first")
i = 0
console.time("Using new with length defined")
while(i<arrsize){
arr[i] = i
i++
}
console.timeEnd("Using new with length defined")
i = 0
arr = new Array(arrsize)
console.time("Using new with length defined again")
while(i<arrsize){
arr[i] = i
i++
}
console.timeEnd("Using new with length defined again")
i = 0
arr = new Array(arrsize)
console.time("simply iterating")
while(i<arrsize){
i++
}
console.timeEnd("simply iterating")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment