这次认真的测试了三种浏览器(ie/firefox/opera)的xmlhttp并发行为,发现如果用户同时发出很多xmlhttp 异步请求,那么浏览器不是一股脑全把请求发出去,而是存在一个最大并发数。我的机器测试发现,ie和ff里面是2,opera是4。
所以说,在设计一个站点时,让ajax页面同时载入数十个xmlhttp请求不是明智的做法。在考虑减少接口耦合的同时,也应该斟酌速度问题。实际上,可以使用某些细化的设计,可以把多种请求绑定到一起发送,从而达到优化的目的。
下面是我的测试代码:
<?php //服务端ajaxserver.php
function _getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
function _exit($msg)
{
echo("$msg\n");
exit();
}
$mode = $_GET["mode"];
$f = fopen("$mode.log", "a+");
if(!$f) _exit();
$begin = _getmicrotime();
$str = "$begin\t". $_GET["flag"] . "\t begin \n";
fwrite($f, "$str");
fclose($f);
echo($str);
sleep(2);
$f = fopen("$mode.log", "a+");
if(!$f) _exit();
$end = _getmicrotime();
$str = "$end\t". $_GET["flag"] . "\t end \n";
fwrite($f, "$str");
fclose($f);
echo($str);
?>
//这是.html网页代码:
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<script language="JavaScript">
<!--
function $(id)
{
return document.getElementById(id);
}
function ajax_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
return A;
}
function doit(flag)
{
var uri = "ajaxserver.php?mode=opera&flag=" + flag ;
var x = ajax_object();
x.open("GET", uri, true);
function callback()
{
if (x.readyState != 4)
return;
if (x.status==200)
{
$("result").value += x.responseText;
}
}
if ("[XMLHttpRequest]"==x.constructor)
{
x.onload = callback ;
}
else
{
x.onreadystatechange = callback ;
}
x.send(null);
}
function doajax()
{
doit(1);
doit(2);
doit(3);
doit(4);
doit(5);
}
//-->
</script>
</head>
<body>
<input type="button" value="doajax" onclick="doajax();">
<textarea cols="80" rows="60" id="result"></textarea>
</body>
</html>
************************************************
下面是测试结果:
IE的测试结果:
1157288179.03 2 begin
1157288179.03 1 begin
1157288181.03 1 end
1157288181.04 2 end
1157288181.05 3 begin
1157288181.06 4 begin
1157288183.05 3 end
1157288183.06 5 begin
1157288183.09 4 end
1157288185.09 5 end
firefox的测试结果
1157288092.36 1 begin
1157288092.38 2 begin
1157288094.36 1 end
1157288094.38 2 end
1157288094.39 3 begin
1157288094.39 4 begin
1157288096.4 4 end
1157288096.42 3 end
1157288096.42 5 begin
1157288098.43 5 end
opera的测试结果:
1157288410.88 1 begin
1157288410.89 4 begin
1157288410.89 2 begin
1157288410.89 3 begin
1157288412.89 1 end
1157288412.89 2 end
1157288412.92 5 begin
1157288412.92 4 end
1157288412.92 5 begin
1157288412.92 3 end
1157288414.93 5 end
1157288414.95 5 end
cited: http://sithere.net/article.asp?id=729&page=3
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1619416