Sunday, November 20, 2016
JavaScript performance test utility script
/* testImplement - specific code we want to test, encapsulated within its own function.
testParams - params test code needs to work, might be an array or single value.
repetitions - number of times test to be run so as to calculate average speed.
Usage:
var testCode = new SpeedTest(testImplement, testParams, repetitions);
testCode.startTest();
*/
function SpeedTest(testImplement, testParams, repetitions) {
this.testImplement = testImplement;
this.testParams = testParams;
this.repetitions = repetitions || 10000;
this.average = 0;
}
SpeedTest.prototype = {
startTest: function () {
var beginTimeMs,
endTimeMs,
sumTimesMs = 0;
//repeat test to find total sum of time taken
for (var i = 0, x = this.repetitions; i < x; i++) {
beginTimeMs = +new Date();//unary converts Date value to numeric ms
this.testImplement(this.testParams);
endTimeMs = +new Date();
sumTimesMs += endTimeMs - beginTimeMs;
};
this.average = sumTimesMs / this.repetitions;
return console.log("Average executions across " +
this.repetitions + ": " +
this.average);
}
}
//Convert poorly written code to test into a function so we can use it as the testImplement parameter
var someArray = ["AAA", "BB", "CCCC", "ZZ"];
var fooList = [];
//poorly written for loop code to test
for (var i = 0; i < someArray.length; i++) {
var newFoo = new Foo(someArray[i]);
fooList.push(newFoo);
};
//wrap above code in a function so we can use it in SpeedTest
var poorCode = function () {
for (var i = 0; i < someArray.length; i++) {
var newFoo = new Foo(someArray[i]);
fooList.push(newFoo);
};
}
//Test Speed version 1 (params are global, so no need to pass in)
var poorCodeTest = new SpeedTest(poorCode, null, 50000);
poorCodeTest.startTest();
//Test Speed version 2 - making use of params list
var testParams = [someArray, fooList];
var poorCodeParams = function (listOfParams) {
for (var i = 0; i < listOfParams[0].length; i++) {
var newFoo = new Foo(listOfParams[0][i]);
listOfParams[1].push(newFoo);
};
}
poorCodeTest = new SpeedTest(poorCodeParams, testParams, 50000);
poorCodeTest.startTest();
//Improved for loop code test
var goodCodeParams = function (listOfParams) {
for (var i = 0, x = listOfParams[0].length; i <x; i++) {
listOfParams[1].push(new Foo(listOfParams[0][i]);
};
}
var goodCodeTest = new SpeedTest(goodCodeParams, testParams, 50000);
goodCodeTest.startTest();
// Note: This snippet was customized from Code School JS Best practices. Excellent online learning site
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment