先贴代码,之后再来补内容
<!DOCTYPE HTML>
<html>
<head>
<title>测试数组push和unshift方法的效率</title>
</head>
<body>
</body>
<script type="text/javascript">
var startTime = 0; /* 开始时间 */
var endTime = 0; /* 结束时间 */
var arr = []; /* 测试数组 */
var n = 50000; /* 插入次数 */
var i = 0; /* 循环基数 */
calculate("unshift"); /* calculate方法测试 */
calculate("push"); /* push方法测试 */
function calculate(method){
i=0;arr = [];
while (i!=n){
if (i==0) {
startTime = new Date(); /* 开始时间获取*/
}
arr[method](i);
i++;
};
endTime = new Date(); /* 结束时间获取 */
console.log(method+" : "+(endTime.getTime()-startTime.getTime())+" 毫秒"); /* 时间差 */
}
</script>
</html>