Manual benchmarking
In computing, a benchmark is the act of running a computer program, a set of programs, or other operations, in order to assess the relative performance of an object, normally by running a number of standard tests and trials against it. The term 'benchmark' is also mostly utilized for the purposes of elaborately designed benchmarking programs themselves.
(source : wikipedia).
Javascript manual benchmarking
Create a start date with "new Date()" and a end date with "new Date()" too, then substract second date to first one to have the result in millisecondes.
Between both, place you code in a hudge loop, then run the code and check the result !
You can launch the test more than one time to be sure, but most of the time the result is sightly the same.
As result depend of computer CPU, the goal is to test 2 functions with same aim at the same time, to determine wich one will be used in production code
Test can be made on Jsfiddle or codepen.io if you want to live test them without creating pages for it.
Code :copy to clipboard
You can launch the test more than one time to be sure, but most of the time the result is sightly the same.
As result depend of computer CPU, the goal is to test 2 functions with same aim at the same time, to determine wich one will be used in production code
Test can be made on Jsfiddle or codepen.io if you want to live test them without creating pages for it.
ts=new Date(); for (w=0 ; w < 100000 ; w++) //place here the code to test console.log('result in '+ (new Date()-ts) +' msec');
For example, a benchmark of two ways to replace all space in a stringcopy to clipboard
var ts; //Testing join method ts=new Date(); for (w=0 ; w < 100000 ; w++) binaryString=binaryString.replace(/ /g ,''); console.log(binaryString +' in '+ (new Date()-ts) +' msec'); //Testing reg exp method ts=new Date(); for (w=0 ; w < 100000 ; w++) binaryString = binaryString.split(' ').join(); console.log(binaryString +' in '+ (new Date()-ts) +' msec');
Another exemple "beautifull" vs "classical" codecopy to clipboard
var result = '',ts; //Classical code ts=new Date() for( i=0 ; i < binaryString.length ; i=i+8 ) result += String.fromCharCode(parseInt(binaryString.substring(i,i+8), 2) ); console.log(result +' in '+ (new Date()-ts) +' msec'); //Beautifull code ts=new Date(); for (w=0 ; w < 100000 ; w++) result = binaryString.match(/([10]{8}|\s+)/g) .map(function(fromBinary) { return String.fromCharCode(parseInt(fromBinary, 2) ); }) .join('');