Created
October 3, 2016 20:12
Star
You must be signed in to star a gist
Array spread vs for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const perfy = require('perfy') | |
function zoomLevelToFactor(level = 0) { | |
// The original size is 0 and each increment above or below | |
// represents zooming 20% larger or smaller to default limits | |
// of 300% and 50% of original size, respectively. | |
if (!level || typeof level !== 'number' || level === 0) return 1; | |
let operator = level < 0 ? -1 : 1; | |
let result = 1; | |
level = (level < 0) ? level * -1 : level; | |
for (let i = 0; i < level; i++) { | |
result = result + (result * .2 * operator); | |
} | |
return result; | |
} | |
function zoomLevelToFactorFancy(level = 0) { | |
// The original size is 0 and each increment above or below | |
// represents zooming 20% larger or smaller to default limits | |
// of 300% and 50% of original size, respectively. | |
if (!level || typeof level !== 'number' || level === 0) return 1; | |
let isNegative = level < 0; | |
return [...Array(Math.abs(level)).keys()].reduce((acc, x) => { | |
return acc + (isNegative ? acc * -1 : acc) * 0.2; | |
}, 1) | |
} | |
const iterations = 50000; | |
function fancy() { | |
perfy.start('fancy') | |
for (let i = 0; i < iterations; i++) { | |
let x = zoomLevelToFactorFancy(4); | |
} | |
return perfy.end('fancy').time | |
} | |
function unfancy() { | |
perfy.start('unfancy') | |
for (let i = 0; i < iterations; i++) { | |
let x = zoomLevelToFactor(4); | |
} | |
return perfy.end('unfancy').time | |
} | |
console.log(`Converting zoom level ${iterations} times:`) | |
console.log(`Fancy: ${fancy()}`) | |
console.log(`Unfancy: ${unfancy()}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results:
Converting zoom level 50000 times:
Fancy: 0.031
Unfancy: 0.002