Last active
November 26, 2022 19:04
-
-
Save RascalTwo/b703f80bb894038c86b7036c0270bb67 to your computer and use it in GitHub Desktop.
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 bench = require('benchmark'); | |
module.exports = (test, ...functions) => { | |
const suite = new bench.Suite(); | |
for (const func of functions) { | |
suite.add(func.name, test.bind(null, func)); | |
} | |
return suite | |
.on('start', () => console.log('Starting benchmark...')) | |
.on('cycle', (event) => { | |
console.log(String(event.target)); | |
}).on('complete', function () { | |
console.log('Fastest is ' + this.filter('fastest').map('name')); | |
}).run({ 'async': true }); | |
} |
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
function reverseString(text) { | |
return text.split("").reverse().join(""); | |
} | |
function reverseStringForLoop(text) { | |
let result = ""; | |
for (let i = text.length - 1; i >= 0; i--) { | |
result += text[i]; | |
} | |
return result; | |
} | |
require('./bench.js')((func) => { | |
func('aeiou'); | |
func('123456789'); | |
func('AsDfGhJkL'); | |
}, reverseString, reverseStringForLoop); | |
/* | |
Starting benchmark... | |
reverseString x 643,832 ops/sec ±2.94% (81 runs sampled) | |
reverseStringForLoop x 1,805,835 ops/sec ±1.54% (87 runs sampled) | |
Fastest is reverseStringForLoop | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment