例如,这两个片段之间存在性能差异:
var my_array = [''];
for (var i = 0; i < 2000; i++) {
my_array[0] += i;
}
和
var my_array = [''];
var my_string = array[0];
for (var i = 0; i < 2000; i++) {
my_string += i;
}
谢谢!
答案 0 :(得分:1)
亲自看看(越低越好)。
var suite = [
function test0() {
var t0, t1;
t0 = performance.now();
var my_array = [''];
for (var i = 0; i < 2000; i++) {
my_array[0] += i;
}
t1 = performance.now();
return t1 - t0;
},
function test1() {
var t0, t1;
t0 = performance.now();
var my_array = [''];
var string = my_array[0];
for (var i = 0; i < 2000; i++) {
string += i;
}
my_array[0] = string;
t1 = performance.now();
return t1 - t0;
}];
var tests = [0, 0];
var amount = [1000, 1000];
function run(test) {
if (amount[test]-- > 0 && test < 2) {
tests[test] += suite[test]();
setTimeout(function(){run(test)}, 0);
} else if (test < 1) {
document.write('<pre>Running test 1 in 1 second</pre>');
setTimeout(function(){
document.write('<pre>Running test 1</pre>');
run(test+1)
}, 1000);
} else {
document.write('<pre>1000 runs complete</pre>');
document.write('<pre>Test 0 total: ' + tests[0] + 'ms</pre>');
document.write('<pre>Test 1 total: ' + tests[1] + 'ms</pre>');
}
}
setTimeout(function(){
document.write('<pre>Running test 0</pre>');
run(0);
}, 1000);
&#13;