Skip to content

Instantly share code, notes, and snippets.

@colus001
Last active October 8, 2018 10:10
Show Gist options
  • Save colus001/002eef7230b1b86ac2188b0d40d8fa1b to your computer and use it in GitHub Desktop.
Save colus001/002eef7230b1b86ac2188b0d40d8fa1b to your computer and use it in GitHub Desktop.
Quick benchmark for Immutable Array

Quick benchmark for merge two arrays with immutable state

CODE

var compare = () => {
  var a = _.range(0, 1000000)
  var b = _.range(1000000, 2000000)

  console.time('spread')
  var c = [...a, ...b]
  console.timeEnd('spread')

  console.time('concat')
  var d = [].concat(a, b)
  console.timeEnd('concat')

  console.time('concat with a')
  var e = a.concat(b)
  console.timeEnd('concat with a')

  console.time('concat prototype')
  var f = Array.prototype.concat(a, b)
  console.timeEnd('concat prototype')
  
  console.time('concat prototype with empty array')
  var g = Array.prototype.concat([], a, b)
  console.timeEnd('concat prototype with empty array')
}
In Chrome
spread: 190.30029296875ms
concat: 10.664794921875ms
concat with a: 11.88818359375ms
concat prototype: 20.571044921875ms
concat prototype with empty array: 20.703125ms
In Safari
spread: 29.738ms
concat: 48.883ms
concat with a: 16.941ms
concat prototype: 24.157ms
concat prototype with empty array: 24.755ms
In Node.js
spread: 151.183ms
concat: 12.076ms
concat with a: 13.202ms
concat prototype: 26.343ms
concat prototype with empty array: 29.401ms
@colus001
Copy link
Author

colus001 commented Oct 8, 2018

Immutable utils for array in response with test result

// @flow
export const append = (arr: Array<any>, item: any | Array<any>): Array<any> => arr
  .concat(item)

export const removeAtIndex = (arr: Array<any>, index: number): Array<any> => arr
  .slice(0, index)
  .concat(arr.slice(index + 1))

export const updateAtIndex = (arr: Array<any>, index: number, item: any): Array<any> => arr
  .slice(0, index)
  .concat(item, arr.slice(index + 1))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment