Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to concatenate strings in nodeJS/JavaScript [duplicate]

I understand that doing something like

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

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?

like image 495
Yotam Avatar asked Dec 13 '12 12:12

Yotam


People also ask

What is the best way to concatenate strings in JavaScript?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.

What is the most efficient way to concatenate many strings together?

When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.

How do you concatenate a string multiple times?

You need [my_string]*3 instead of my_string*3 because you want a list containing the string three times (that can then be joined) instead of having a single big string containing the message three times. Also, " ". join(a) is shorthand for str. join(" ", a) .


2 Answers

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.

Tested with the following code:

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

Output:

Normal took: 4 ms. Buffer took: 458 ms. 
like image 59
Mustafa Avatar answered Oct 11 '22 13:10

Mustafa


There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slower than just +

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

Simply put: + is the fastest.

like image 38
Cerbrus Avatar answered Oct 11 '22 13:10

Cerbrus