- ОБНОВЛЕНО --- ОПТИМИЗИРОВАННЫЙ КОД ---
Я сделал небольшой тест и вот результаты
для 1000 итераций,
XML-объект занял 4270 мс
Простое добавление тега скрипта заняло 4169 мс;
Мощный XHR с использованием функции Eval дал 3206 мс;// Самый быстрый
Для справки здесь приведены сценарии на стороне клиента и на сервере.
Script 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 работала намного быстрее!