Benchmark.js
by David Adler
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<ul id='cycleResults'>
</ul>
<div id="result">
</div>
<br>
<button id="btn">
Run Tests
</button>
JavaScript
const emptyArray = (n) => [...Array(n)].map(x => undefined)
const keys = emptyArray(100000).map(x => Math.random().toString())
const randomChar = () => String.fromCharCode(Math.floor(Math.random() * 60) + 96)
const randomProperty = () => Math.random() > 0.5 ? {[randomChar]: randomChar } : undefined
const createItem = (id) => ({ id, text: 'asdf ' + id, sentAt: new Date(), ...randomProperty() })
const map1 = new Map()
const map2 = {}
keys.map(x => map1.set(x, createItem(x)))
keys.map(x => map2[x] = createItem(x))
function test1()
{
const ret = keys.map(x => map1.get(x))
return ret
}
function test2()
{
const ret = keys.map(x => map2[x])
return ret
}
var cycleResults = document.getElementById('cycleResults');
var result = document.getElementById('result');
var btn = document.getElementById('btn');
// BENCHMARK ====================
btn.onclick = function runTests(){
btn.setAttribute('disable', true);
cycleResults.innerHTML = '';
result.textContent = 'Tests running...';
var suite = new Benchmark.Suite;
// add tests
suite
.add('test1', test1)
.add('test2', test2)
// add listeners
.on('cycle', function(event) {
var result = document.createElement('li');
result.textContent = String(event.target);
document.getElementById('cycleResults')
.appendChild(result);
})
.on('complete', function() {
result.textContent = 'Fastest is ' + this.filter('fastest').pluck('name');
btn.setAttribute('disable', false);
})
// run async
.run({ 'async': true });
};