MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

at master 49 lines 1.5 kB view raw
1const ITERATIONS = 1_000_000; 2const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 3const mapFn = x => x * 2; 4 5// --- Polyfill --- 6const ArrayFrom_polyfill = function (src, mapFn, thisArg) { 7 if (src == null) { 8 console.error('TypeError: Cannot convert undefined or null to object'); 9 return []; 10 } 11 if (mapFn !== undefined && typeof mapFn !== 'function') { 12 console.error('TypeError: mapFn is not a function'); 13 return []; 14 } 15 const arr = []; 16 let i = 0; 17 if (src[Symbol.iterator] != null) { 18 for (const v of src) arr.push(mapFn ? mapFn.call(thisArg, v, i++) : v); 19 } else { 20 const len = src.length >>> 0; 21 for (; i < len; i++) arr.push(mapFn ? mapFn.call(thisArg, src[i], i) : src[i]); 22 } 23 return arr; 24}; 25 26// --- Builtin --- 27function benchBuiltin() { 28 const start = performance.now(); 29 for (let i = 0; i < ITERATIONS; i++) { 30 Array.from(source, mapFn); 31 } 32 return performance.now() - start; 33} 34 35// --- Polyfill --- 36function benchPolyfill() { 37 const start = performance.now(); 38 for (let i = 0; i < ITERATIONS; i++) { 39 ArrayFrom_polyfill(source, mapFn); 40 } 41 return performance.now() - start; 42} 43 44const builtinMs = benchBuiltin(); 45const polyfillMs = benchPolyfill(); 46 47console.log(`Array.from (builtin): ${builtinMs.toFixed(2)} ms`); 48console.log(`Array.from (polyfill): ${polyfillMs.toFixed(2)} ms`); 49console.log(`Ratio: builtin is ${(polyfillMs / builtinMs).toFixed(2)}x ${polyfillMs > builtinMs ? 'faster' : 'slower'} than polyfill`);