Skip to content

Instantly share code, notes, and snippets.

@martinwheeler
Created April 17, 2017 01:13
Show Gist options
  • Save martinwheeler/10f90ee350183c2055278e42e97786b5 to your computer and use it in GitHub Desktop.
Save martinwheeler/10f90ee350183c2055278e42e97786b5 to your computer and use it in GitHub Desktop.
Just a simple way to see how slow your code gets when using eval().
function doSomething( str, a ) {
eval( str );
console.log(a);
}
function getRandomInt( min, max ) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor( Math.random() * ( max - min ) ) + min;
}
var average = [], t0 = 0, t1 = 0;
for ( let i = 0; i < 10; i++ ) {
t0 = performance.now();
doSomething(`a=${ getRandomInt( 1, 1000 ) };`, ( getRandomInt(1, 1000) * i ));
t1 = performance.now();
average.push( t1 - t0 );
}
function getAverage(params) {
let totaledAverage = 0;
params.forEach(param => {
totaledAverage += param;
});
return ( totaledAverage / params.length );
}
console.log('Average: ' + getAverage(average));
// eval average: 0.21049999999959254
// non-eval average: 0.12049999999999272
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment