Skip to content

Instantly share code, notes, and snippets.

@timoxley
Last active October 1, 2016 16:21
Show Gist options
  • Select an option

  • Save timoxley/b6463357aaea004711d8583142299de4 to your computer and use it in GitHub Desktop.

Select an option

Save timoxley/b6463357aaea004711d8583142299de4 to your computer and use it in GitHub Desktop.
Quick benchmark of various iteration styles
'use strict'
const tests = [
test(testFor),
test(testForAlt),
test(testForEach),
test(testReduceFunction),
test(testReduceArrows),
test(testForOf)
]
console.log(tests.length)
/**
* Test Cases
*/
function testFor (items) {
let result = 0
for (let i = 0; i < items.length; i++) {
result += items[i]
}
return result
}
function testForAlt (tokens) {
let result = 0
for (let i = 0, token; (token = tokens[i]); i++) {
const token = tokens[i]
result += token
}
return result
}
function testForEach (items) {
let result = 0
items.forEach((item) => {
result += item
})
return result
}
function testReduceArrows (items) {
return items.reduce((c, item) => c += item)
}
function testReduceFunction (items) {
return items.reduce(function (c, item) {
return c += item
})
}
function testForOf (items) {
let result = 0
for (let item of items) {
result += item
}
return result
}
/**
* Fixture generator
*/
function generate (size = 10000000) {
const items = []
for (let i = 0; i < size; i++) {
items.push(Math.random())
}
return items
}
/**
* Test Runner
*/
function test (testFn) {
const items = generate()
const name = testFn.name.replace('test', '')
console.time(name)
const result = testFn(items)
console.timeEnd(name)
return result
}
For: 186.791ms
ForAlt: 270.132ms
ForEach: 458.686ms
ReduceFunction: 321.777ms
ReduceArrows: 334.990ms
ForOf: 1565.900ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment