Yot*_*tam 52 javascript string concatenation node.js
我明白做的事情就像
var a = "hello";
a += " world";
Run Code Online (Sandbox Code Playgroud)
它是相对非常慢的,因为浏览器会这样做O(n)
.没有安装新库,有没有更快的方法?
Mus*_*afa 17
问题已经得到解答,但是当我第一次看到它时,我想到了NodeJS Buffer.但它比+更慢,所以很可能在字符串中没有任何东西比+更快.
使用以下代码进行测试:
function a(){
var s = "hello";
var p = "world";
s = s + p;
return s;
}
function b(){
var s = new Buffer("hello");
var p = new Buffer("world");
s = Buffer.concat([s,p]);
return s;
}
var times = 100000;
var t1 = new Date();
for( var i = 0; i < times; i++){
a();
}
var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
b();
}
var t3 = new Date();
console.log("Buffer took: " + (t3-t2) + " ms.");
Run Code Online (Sandbox Code Playgroud)
输出:
Normal took: 4 ms.
Buffer took: 458 ms.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
172700 次 |
最近记录: |