在NodeJS/JavaScript中串联字符串的快速方法 [英] Fast way to concatenate strings in nodeJS/JavaScript

查看:187
本文介绍了在NodeJS/JavaScript中串联字符串的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解这样做

var a = "hello";
a += " world";

它相对非常慢,因为浏览器在O(n)中执行该操作.有没有安装新库的更快方法?

It is relatively very slow, as the browser does that in O(n) . Is there a faster way of doing so without installing new libraries?

推荐答案

该问题已经回答,但是当我第一次看到它时,我想到了NodeJS Buffer.但这比+慢得多,因此在字符串隐构中,没有什么比+快.

The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.

使用以下代码进行了测试:

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.");

输出:

Normal took: 4 ms.
Buffer took: 458 ms.

这篇关于在NodeJS/JavaScript中串联字符串的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆