Home Search Member List Faq Register Login  
JavaScript Tips
Concatenate your strings efficiently

Thread Starter: Karamasoft   Started: 09-18-2007 12:41 PM   Replies: 0
 Karamasoft Support Forums » General Discussions » JavaScript Tips » Concatenate your strings efficiently
 Printable Version    « Previous Thread   Next Thread »
  18 Sep 2007, 12:41 PM
Karamasoft is not online. Last active: 5/8/2018 10:36:45 AM Karamasoft

Top 10 Posts
Joined on 09-05-2004
Posts 6,820
Concatenate your strings efficiently

Even though it is easy to concatenate strings using the + operator, string operations become very costly in terms of CPU cycle when the strings get bigger and there are a lot of strings to concatenate.

The better alternative is to create your own StringBuilder JavaScript object that is similar to the StringBuilder object in the .NET Framework. You can define your StringBuilder object with a buffer array property to store the strings to concatenate.

Then add an Append method to add a string to the buffer array. The JavaScript Array object provides a join method that puts all the elements of an array into a string separated by a specified delimiter. ConvertToString method will join all elements of the buffer array into a string.

function StringBuilder() {

this.buffer = [];


StringBuilder.prototype.Append = function(str) {

this.buffer[this.buffer.length] = str;


StringBuilder.prototype.ConvertToString = function() {

return this.buffer.join('');


Instead of the following:

var str = 'This ' + 'is ' + 'a ' + 'test';

You can now use the following:

var sb = new StringBuilder;

sb.Append('This ');

sb.Append('is ');

sb.Append('a ');


var str = sb.ConvertToString();

Our tests indicated that concatenating the string 'test' 50,000 times using the StringBuilder Append method worked 10 times faster than using the + operator in Internet Explorer.

 Page 1 of 1 (1 items)
Karamasoft Support Forums » General Discussions » JavaScript Tips » Concatenate your strings efficiently

You can add attachments
You can post new topics
You can reply to topics
You can delete your posts
You can edit your posts
You can create polls
You can vote in polls
Forum statistics are enabled
Forum is unmoderated

© 2002-2019 Karamasoft LLC. All rights reserved.