You are here: irt.org | FAQ | JavaScript | General | Q1704 [ previous next ]
The following shows one approach to performance testing JavaScript:
<script language="JavaScript"><!-- // Define a Test object construtor: function Test(loop, testFunction, description) { this.loop = loop; this.invokeFunction = testFunction; this.description = description; this.execute = runTest; this.result = getResult; this.elapsedTime = 0; this.counter = 0; } // Define the Test object execute() method: function runTest() { var start = new Date(); for (var i=0; i<this.loop; i++) this.invokeFunction(); var end = new Date(); this.elapsedTime += (end - start) / this.loop; this.counter++; } // Define the Test object result() method: function getResult() { return this.description + ' : time taken (ms) : ' + (this.elapsedTime/this.counter); } // Define how many times we want to loop around each test: var loop = 10; // Create an array of tests: var tests = new Array( new Test(loop, testFunction1, 'multiple document.write'), new Test(loop, testFunction2, 'single document.write'), new Test(loop, function () { var o = ''; for (var i=0; i<1000; i++) o += i; document.write(o); }, 'anonymous function'), new Test(loop, function () {}, 'do nothing') ) // Comment out any output generated by the running of the tests: document.write('<!--'); // Run each test: for (var i=0; i<tests.length; i++) { tests[i].execute(); } document.write('-->'); // Display results of each test: var output =''; for (var i=0; i<tests.length; i++) { output += tests[i].result() + '\n'; } alert(output); //--></script>