Skip to content

Instantly share code, notes, and snippets.

@alowdon
Last active November 30, 2021 10:05
Show Gist options
  • Save alowdon/0580047afb245a2c462c962b02a685a3 to your computer and use it in GitHub Desktop.
Save alowdon/0580047afb245a2c462c962b02a685a3 to your computer and use it in GitHub Desktop.
Running Benchmark.js tests using Playwright
<!DOCTYPE html>
<html>
<head>
<title>Benchmark.js test</title>
<meta charset="utf-8">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/benchmark@2.1.4/benchmark.min.js"></script>
<script src="bench.js"></script>
</body>
</html>
const suite = new Benchmark.Suite();
const values = [];
for (let i = 0; i < 1000000; i++) {
values.push(i);
}
function some(list, predicate) {
if (list == null) {
return false;
}
for (let i = 0; i < list.length; i++) {
if (predicate(list[i], i)) {
return true;
}
}
return false;
}
suite
.add('Array.prototype.some', () => {
const processed = values.some(value => value > 990000);
})
.add('for loop', () => {
const processed = some(values, value => value > 990000);
})
.on('cycle', event => {
const benchmark = event.target;
console.log(benchmark.toString());
})
.on('complete', () => console.log('Benchmark suite complete.'))
.run();
const { test } = require('@playwright/test');
test('Run benchmarks', async ({ page }) => {
let benchmarkPromise = new Promise(resolve => {
page.on('console', async message => {
if (message.text() === 'Benchmark suite complete.') {
// if the suite has finished, we're done
resolve();
} else {
// pipe through any other console output
console[message.type()](message);
}
});
});
await page.goto(`file://${process.cwd()}/bench.html`);
await benchmarkPromise;
});
@RoyalIcing
Copy link

I forked this and added more benchmarks of various interesting tasks. I also run them in GitHub actions: https://github.com/BurntCaramel/browser-workout Thanks!

@alowdon
Copy link
Author

alowdon commented Nov 30, 2021

Nice one @BurntCaramel 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment