A quick way to concatenate strings in nodeJS / JavaScript

I understand that something like

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

This is relatively slow as the browser does this in O(n) . Is there a faster way to do this without installing new libraries?

+46
javascript string concatenation
Dec 13 '12 at 12:07
source share
4 answers

This is the fastest way to concatenate strings in javascript.

See details

Why is string concatenation faster than array concatenation?

JavaScript: how to merge / merge two arrays to combine into one array?

+32
Dec 13 '12 at 12:15
source share

The question has already been answered, however, when I first saw it, I thought about NodeJS Buffer. But this is slower than +, therefore, most likely, nothing can be faster than + in line consonation.

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

Exit:

 Normal took: 4 ms. Buffer took: 458 ms. 
+12
Dec 14
source share

There is no other way to concatenate strings in JavaScript.
Theoretically, you can use .concat() , but the path is slower than just +

Libraries are more often than no slower than native JavaScript, especially for basic operations such as string concatenation or numerical operations.

Simply put: + is the fastest.

+8
Dec 13 '12 at 12:15
source share

You asked about performance. See perf test comparing "concat", "+" and "join" - in short, the + operator wins far.

+1
Nov 12 '14 at 23:58
source share



All Articles