2019/10/11

[note] 字串加法速度

##ReadMore##
結論:這年頭的browser字串可以用+了

原始碼:
console.time("A01");
var a ="a";for(var i=0;i<100000;i++)a= i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A01");
console.time("A02");
var a ="a";for(var i=0;i<100000;i++)a=[i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A02");
console.time("A01");
var a ="a";for(var i=0;i<100000;i++)a= i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A01");
console.time("A02");
var a ="a";for(var i=0;i<100000;i++)a=[i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A02");
console.time("A01");
var a ="a";for(var i=0;i<100000;i++)a= i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A01");
console.time("A02");
var a ="a";for(var i=0;i<100000;i++)a=[i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A02");

console.time("A03");
var a ="a";for(var i=0;i<10000;i++)a= a+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A03");
console.time("A04");
var a ="a";for(var i=0;i<10000;i++)a=[a,i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A04");
console.time("A03");
var a ="a";for(var i=0;i<10000;i++)a= a+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A03");
console.time("A04");
var a ="a";for(var i=0;i<10000;i++)a=[a,i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A04");
console.time("A03");
var a ="a";for(var i=0;i<10000;i++)a= a+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a"+i+"a";
console.timeEnd("A03");
console.time("A04");
var a ="a";for(var i=0;i<10000;i++)a=[a,i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a",i,"a"].join("");
console.timeEnd("A04");
chrome結果,用join速度遠輸用+
VM140:3 A01: 37.632080078125ms
VM140:6 A02: 64.122802734375ms
VM140:9 A01: 31.302001953125ms
VM140:12 A02: 69.2890625ms
VM140:15 A01: 30.1640625ms
VM140:18 A02: 65.69091796875ms
VM140:22 A03: 14.315185546875ms
VM140:25 A04: 1094.155029296875ms
VM140:28 A03: 4.72900390625ms
VM140:31 A04: 1112.144775390625ms
VM140:34 A03: 4.3271484375ms
VM140:37 A04: 1108.628173828125ms
ie11結果,join略慢,正常情況下輸chrome
A01: 247.3 毫秒
A02: 192.6 毫秒
A01: 221.4 毫秒
A02: 192 毫秒
A01: 207 毫秒
A02: 200.7 毫秒
A03: 23.9 毫秒
A04: 15.8 毫秒
A03: 22.5 毫秒
A04: 17.4 毫秒
A03: 22.9 毫秒
A04: 16.2 毫秒

沒有留言: