While doing some JavaScript performance tests I came up with the following piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Performance Test</title>
<script>
var time1;
var time2;
var executionTime;
function writeALot(){
time1 = new Date().getTime();
var n = Number(document.getElementById("numberOfWrites").value);
var strBuffer = "";
document.getElementById("div1").innerHTML = "";
for (var i = 1; i <= n; i++) {
strBuffer += i + "<br />";
}
document.getElementById("div1").innerHTML = "Number of Writes: " + n + "<br />";
document.getElementById("div2").innerHTML = strBuffer;
}
function printExeTime(){
time2 = new Date().getTime();
executionTime = ((time2 - time1) / 1000).toString();
document.getElementById("div1").innerHTML += "Execution Time: " + executionTime + " seconds";
}
</script>
</head>
<body>
<div id="inputDiv">
Number Of Writes
<br/>
<input type="text" id="numberOfWrites" value="10000">
</input><input type="button" value="Go" onclick="writeALot();printExeTime()">
</div>
<br/>
<div id="div1">
</div>
<div id="div2">
</div>
</body>
</html>
Basically what this does is count from 0 to the number in the text box (10000 default) concatenating each number and a "<br>
" tag on a String, replaces the content of a Div with this String and shows the "time" I took to do the operation.
I did this to test how fast can generated content be printed on the document. While trying out this code I noticed couple of problems:
When you hit the go button for the first time, after a page refresh, the code runs a lot faster than the next attempts. For numbers less than 1000 after the second time the button is hit it might take like twice the amount of time it took to execute the same code for the first time, but once you start raising the number 100000 for example the difference in execution time get a lot bigger.
Try it yourself and see, load the page, hit the button once, code will execute fast, then hit the button again and see the diference? If the Same code is executed why does it takes so long after the first time?
The other thin I notices is that for some reason the way I measuring time is not working properly, seems like I'm getting a new date at the wrong moment, is there something like an event that's fired after the content on a div is modified?