JavaScript Best Practicies : Performance Calculation

Test the speed of code with console.time

var firstRegimentNewbs = ["Grimble Horsehead", "Jark Winterborn", "Bunder Ropefist",
                          "Ernst Breadbaker"];
var firstRegimentKnights = [ *...tons of Knight objects...* ];
console.time("Time to add " + firstRegimentNewbs.length + " Knights");
for(var i = 0, x = firstRegimentNewbs.length; i

Multiple timers can run at one time.

var firstRegimentNewbs = ["Grimble Horsehead", "Jark Winterborn", "Bunder Ropefist",
                          "Ernst Breadbaker"];
var firstRegimentKnights = [ *...tons of Knight objects...* ];
var secondRegimentNewbs = ["Jenner Pond", "Tar Backstrand", "Cromer Treen", "Stim Lancetip",
                           "Vorn Sharpeye", "Rack Leaflets", "Bruck Valleyhome", "Arden Follower"];
var secondRegimentKnights = [ *...tons of Knight objects...* ];
console.time("Total completion time");
for(var i = 0, x = firstRegimentNewbs.length; i

Retrieving and using numerical time data
To accurately generate numerical data we can manipulate, we'll first examine the JavaScript Date object.
Placing a + unary operator in front of Date object variable asks for the specific value in milliseconds.

var rightNow = +new Date();

Implementation of speed test class

function SpeedTestClass(testImplementation, testParams, repetitions) {
  this.testImplementation = testImplementation;
  this.testParams = testParams;
  this.repetitions = repetitions || 10000;
  this.average = 0;
}
SpeedTestClass.prototype = {
  startTest: function() {
    var beginTime, endTime, sumTimes = 0;
    for (var i = 0, x = this.repetitions; i < x; i++){
      beginTime = +new Date();
      this.testImplement( this.testParams );
      endTime = +new Date();
      sumTimes += endTime - beginTime;
    }
    this.average = sumTimes / this.repetitions;
    return console.log("Average execution across " + this.repetitions + ": " + this.average);
  }
}

How to use created class:

var firstRegimentNewbs = ["Grimble Horsehead", "Jark Winterborn",
                          "Bunder Ropefist", "Ernst Breadbaker"];
var firstRegimentKnights = [ *...tons of Knight objects...* ];
var listsForTests = [ firstRegimentNewbs, firstRegimentKnights ];

var BP = function ( listOfParams ){
  for(var i = 0, x = listOfParams[0].length; i < x; i++) {
    listOfParams[1].push(new Knight(listOfParams[0][i], 1));
  }
};

var BPtest = new SpeedTest(noBP, listsForTests, 100000); 
BPtest.startTest();

Leave a Reply

Your email address will not be published. Required fields are marked *