Skip to content

Instantly share code, notes, and snippets.

@ivanseidel
Last active February 18, 2017 13:47
Show Gist options
  • Save ivanseidel/39b982eb60d31c5a11d885fc4018406e to your computer and use it in GitHub Desktop.
Save ivanseidel/39b982eb60d31c5a11d885fc4018406e to your computer and use it in GitHub Desktop.
Redux's benchmarks
//
// Created by Ivan Seidel, Feb/2017
//
// This is a efficiency comparision on state manipulation of arrays
// using ~push~ and ~spread~ operator.
//
// Reason why I did this:
// while getting in sync with current JS/Nodejs tools around the web,
// I got myself digging into Redux's example codes and good practices.
// One of those, was to always use pure functions. Always re-create
// your new state after some change occurs.
// As I wans't sure about Ecmascript's spread operator efficiency on
// doing such thing, I wrote this benchmark program to test their
// difference.
//
// Test ran on:
// `MacBook Pro (Retina, 13-inch, Late 2013)`
//
// Node version:
// v6.9.1
//
// Output:
// > [ 4 ms ] 20000 times executing doNothing
// > [ 21 ms ] 20000 times executing doCreateArray
// > [ 420 ms ] 20000 times executing doCreateArrayWithSlice
// > [ 2614 ms ] 20000 times executing doCreateArrayLikeRedux
//
// Right pad string with wanted char
function pad(string, len, fill = ' ') {
string = string || ''
while (string.length < len) {
string = string + fill
}
return string
}
// Run a function a number of times and logs the time taken
function makeItBurn(exec, times) {
let begin = Date.now()
for (let i = 0; i < times; i++)
exec()
let endin = Date.now()
console.log( pad(`[ ${endin - begin} ms ]`, 16), `${times} times executing ${exec.name}`)
return (endin - begin)
}
function doNothing(){
// Do nothing
}
var data = []
const REPEAT_INNER_LOOP = 60
// Create an array. Add something to it a few times
function doCreateArray(){
data = []
for (let times = 0; times < REPEAT_INNER_LOOP; times++) {
data.push({value: data.length})
}
}
// Create an array. Add something to it a few times by copying it first
function doCreateArrayWithSlice(){
data = []
for (let times = 0; times < REPEAT_INNER_LOOP; times++) {
data = data.slice()
data.push({value: data.length})
}
}
// Create an array. Add something to it a few times by recreating the array
function doCreateArrayLikeRedux(){
data = []
for (let times = 0; times < REPEAT_INNER_LOOP; times++) {
data = [...data, {value: data.length}]
}
}
const TIMES = 20000
makeItBurn(doNothing, TIMES)
makeItBurn(doCreateArray, TIMES)
makeItBurn(doCreateArrayWithSlice, TIMES)
makeItBurn(doCreateArrayLikeRedux, TIMES)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment