benchmark.js
Simple benchmarking script for Javascript functions to compare execution times.
Usage
The more iterations you choose the more accurate the benchmarking results will be, note that choosing a high amount of iterations will take a long time for the benchmark to complete.
iterations parameter takes an interger number for how many loops you want the benchmark to run, function1 and function2 parameters should be javascript function(){ // code } or () => { // code } function code blocks.
<script src="bjs.min.js"></script>
<script>
bjs(iterations, function1, function2);
</script>
Example
I want to compare getting the current minutes with leading zero's, using the short-if statement or slice function so I use benchmark.js as follows:
<script src="bjs.min.js"></script>
<script>
var dateObj = new Date();
var minutes = dateObj.getMinutes();
var voidVar;
bjs(1000000, function(){
voidVar = ('0'+minutes).slice(-2);
},
function(){
voidVar = (minutes < 10 ? '0' : '') + minutes;
});
bjs(100000, () => {voidVar = ('0'+minutes).slice(-2)}, () => {voidVar = (minutes < 10 ? '0' : '') + minutes});
</script>
Output
Output is send to the Browser's console as an object (console.log is used):
{
"Function 1": "2.611s (2611ms)"
"Function 2": "1.735s (1735ms)"
"iterations": 10000000
}