js中也是有线程概念的,setTimeout,setInterval和ajax都是这样的例子,另起一个线程,时间上似乎是并行处理的。于是,我想是不是可以利用这个多线程的机制,优化一下大数量数据遍历时的性能问题呢?
写了个demo如下:
====================================================
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿当制作</title>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
<div id="box6"></div>
<div id="box7"></div>
<div id="box8"></div>
<p>方法1耗时:<span id="time1"></span>微秒</p>
<p>方法2耗时:<span id="time2"></span>微秒</p>
<script type="text/javascript">
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var box4 = document.getElementById("box4");
var box5 = document.getElementById("box5");
var box6 = document.getElementById("box6");
var box7 = document.getElementById("box7");
var box8 = document.getElementById("box8");
var time1 = document.getElementById("time1");
var time2 = document.getElementById("time2");
function addItems(box,str,color,callback){
function addItem(){
var node = document.createElement("span");
node.innerHTML = str;
node.style.color = color;
box.appendChild(node);
}
for(var i=0;i<9999;i++){
addItem();
}
if(callback) callback();
}
function testFun(){
var t = new Date().getTime();
addItems(box1,"1","blue");
addItems(box2,"2","green");
addItems(box3,"3","red");
addItems(box4,"4","yellow");
var t2 = new Date().getTime();
time1.innerHTML = t2 - t;
}
function testFun2(){
var t2,n = 0,t = new Date().getTime();
setTimeout(function(){addItems(box5,"1","blue",callback);},0);
setTimeout(function(){addItems(box6,"2","green",callback);},0);
setTimeout(function(){addItems(box7,"3","red",callback);},0);
setTimeout(function(){addItems(box8,"4","yellow",callback);},0);
function callback(){
n++;
if(n==4){
t2 = new Date().getTime();
time2.innerHTML = t2 - t;
}
}
}
testFun();
testFun2();
</script>
</body>
</html>
====================================================
思路很简单,我有8个div容器,想给每个容器里填入9999个span元素。4个一组,想看看一个线程串行处理的速度快,还是分4个线程并行处理的速度快。
结果很意外:
=====================
在firefox下
在chrome下
在opera下
在ie8下
除了在opera这个怪胎下多线程的方式快了一点儿,别的浏览器下都是单线程更快。(可是,opera怎么把我的输出输了三遍啊?这何解啊?+_+)
我猜js所谓的“多线程”,其实还是单线程,只是cpu把任务时间分成了一小段一小段,然后分别去处理这多个线程,同一时间只有一个线程可以被处理。如果线程越多,反而越让cpu频于在多个任务间切换,反而影响了速度。