Skip to content

Instantly share code, notes, and snippets.

@Chunlin-Li
Created November 26, 2015 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chunlin-Li/c49d6be2e9179cc26c95 to your computer and use it in GitHub Desktop.
Save Chunlin-Li/c49d6be2e9179cc26c95 to your computer and use it in GitHub Desktop.
node / javascript performance: string concat operator (+) vs array.join()

Performance Comprison:

Section 1 :

string concatenate operator, for short string but large times.

Section 2 :

array join(), for short string but large times.

node version : v4.1.2 platform: Intel I7, 16G DDR3, Ubuntu x64

start = process.hrtime();
for(let i = 0 ; i < N; i++) {
    string = 'asdfjkl' + i +  '#' + (i * 2) + 'okaneinij';
}
console.log('section 1 : ' + timeUse(start));



var string2;
start = process.hrtime();
for(let i = 0 ; i < N; i++) {
    string2 = ['asdfjkl', i,  '#', (i * 2), 'okaneinij'].join(' ');
}
console.log('section 2 : ' + timeUse(start));

result:

# N : 1K
section 1 : 139679ns
section 2 : 1028747ns

# N : 1M
section 1 : 176692203ns
section 2 : 567614619ns

many string concatenate to one long string.

start = process.hrtime();
for(let i = 0 ; i < N; i++) {
    string += i.toString();
}
console.log('section 1 : ' + timeUse(start));


start = process.hrtime();
for(let i = 0 ; i < N; i++) {
    ary.push(i.toString());
}
ary.join(' ');
console.log('section 2 : ' + timeUse(start));

result :

# N : 10
section 1 : 85186ns
section 2 : 28666ns

# N : 100
section 1 : 120392ns
section 2 : 49320ns

# N : 10K
section 1 : 3127081ns
section 2 : 3803529ns
@shaunc
Copy link

shaunc commented Jun 29, 2017

In the 2nd test, why do you use join(' ') not join('')?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment