JS版Stopwatch计时器
写了一个类似一个C#版Stopwatch计数器的JS代码,很简单:
现在我用它来进行MS AJAX的StringBuilder,和普通字符串String的拼接的效率比较:
最后得到效率比较,在循环次数多的情况下,stringBuilder明显比string快。
function Stopwatch()
{
this.startDate = null;
this.endDate = null;
this.elapsedMilliseconds = null;
this.start = function()
{
this.startDate = new Date();
}
this.stop = function()
{
this.endDate = new Date();
this.elapsedMilliseconds = this.endDate - this.startDate;
}
// this.reset = function()
// {
// this.startDate = null;
// this.endDate = null;
// }
}
{
this.startDate = null;
this.endDate = null;
this.elapsedMilliseconds = null;
this.start = function()
{
this.startDate = new Date();
}
this.stop = function()
{
this.endDate = new Date();
this.elapsedMilliseconds = this.endDate - this.startDate;
}
// this.reset = function()
// {
// this.startDate = null;
// this.endDate = null;
// }
}
现在我用它来进行MS AJAX的StringBuilder,和普通字符串String的拼接的效率比较:
Sys.Application.add_load(
function()
{
var watch = new Stopwatch();
var temp;
var stringBuilder = new Sys.StringBuilder();
watch.start();
for(var i = 0; i < 10000; i++)
{
stringBuilder.append("a");
}
temp = stringBuilder.toString();
watch.stop();
alert("ms ajax's stringBuilder: " + watch.elapsedMilliseconds + "ms");
var str = "";
watch.start();
for(var i = 0; i < 10000; i++)
{
str += "a";
}
watch.stop();
alert("string: " + watch.elapsedMilliseconds + "ms");
}
);
function()
{
var watch = new Stopwatch();
var temp;
var stringBuilder = new Sys.StringBuilder();
watch.start();
for(var i = 0; i < 10000; i++)
{
stringBuilder.append("a");
}
temp = stringBuilder.toString();
watch.stop();
alert("ms ajax's stringBuilder: " + watch.elapsedMilliseconds + "ms");
var str = "";
watch.start();
for(var i = 0; i < 10000; i++)
{
str += "a";
}
watch.stop();
alert("string: " + watch.elapsedMilliseconds + "ms");
}
);
最后得到效率比较,在循环次数多的情况下,stringBuilder明显比string快。