- 更新---優化的代碼---
我做了一個小的基準,這裏的結果
1000次迭代,
XML對象花費了4270ms
一個簡單的腳本標籤添加了4169ms;
使用Eval函數的一個強大的XHR給了3206ms; //最快
此處參考的是客戶端和服務器端腳本。
腳本2.PHP
<?php
echo trim('
var dunce = {
menu : {
id:1,
gohan:"goku blah blah blah"
}
};
console.log(dunce.menu.id); // yeah its still faster
iteration++;
if(iteration<1000){
ScriptTAG();
}else{
console.log("Total time taken for "+iteration+"iterations is "+ (new
Date().getTime()-start));
}');
?>
的script.php [XML輸出]
<?php
header ("Content-Type:text/xml");
echo"<menu><id>1</id><gohan>Goku blah blah blah</gohan></menu>";
?>
客戶端文件
var iteration = 0;
// Use XHR
var start ;
// Use console for firing these
function XHR() {
if(iteration == 0) {
start = new Date().getTime();
}
var io = new XMLHttpRequest();
io.open("POST",'script.php',true);
io.onload = function() {
iteration++;
if(iteration<1000) {
XHR();
} else {
alert("Total time taken for "+iteration+"iterations is "+ (new Date().getTime()-start));
}
}
io.send();
}
function AlterXHR(){
// EVAL IDEA
if(iteration == 0){
start = new Date().getTime();
}
var io = new XMLHttpRequest();
io.open("POST",'script2.php',true);
io.onload = function(){
eval(io.responseText);
}
io.send();
}
function ScriptTAG() {
if(iteration == 0) {
start = new Date().getTime();
}
var script = document.createElement('script');
script.src = "script2.php";
document.head.appendChild(script);
}
ScriptTAG(); // Replace this with whatever u want to test! and run!!
我認爲這裏的差異是因爲本地JavaScript的純粹對象通過XML Parser進行更快的編譯。
正如你可以看到與NATIVE EVAL功能相同的腳本工作方式更快!
爲什麼地獄script.php有內容類型文本/ JavaScript? – Raynos
轉到XHR方式,你有更好的基於事件的系統,並告訴你它是否失敗,但是沒有辦法通過腳本標籤方式檢查上述內容。它也允許你以更好的方式處理輸出,然後腳本標記! – ShrekOverflow
@Raynos很好的問題,這就是我想知道的,也許他只是發送一個JSON對象,如說 內容= {「x」:「等等」}; – ShrekOverflow