Created
March 4, 2020 01:25
-
-
Save poychang/36e9dbb1ce1f40f59140961cf923fc33 to your computer and use it in GitHub Desktop.
[比較 Array 和 Generator 的作法]
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
// 搭配 Quokka.js 來測試會比較方便看 | |
function* rangeGenerator(start, end) { | |
for (let i = start; i < end; i++) yield i; | |
} | |
function range(start, end) { | |
return Array.from({ length: end - start }, (_, i) => i + start); | |
} | |
let MAX = 1_000_000; | |
console.time('generator'); | |
console.log([...rangeGenerator(1, MAX)].length); | |
console.timeEnd('generator'); | |
console.time('array'); | |
console.log(range(1, MAX).length); | |
console.timeEnd('array'); | |
// generator: 227.949ms | |
// array: 371.532ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment