Click here to Skip to main content
15,879,535 members
Articles / Web Development / HTML
Article

JavaScript StringBuilder

Rate me:
Please Sign up or sign in to vote.
4.82/5 (43 votes)
6 Dec 2005CPOL2 min read 245.5K   2.1K   68   34
An extremely simple, light-weight JavaScript StringBuilder class. Hundreds of times faster than string concatenation in IE.

Introduction

Once upon a time, not so long ago, pushing any significant processing to the client browser was considered a bad practice. Now with the rise in popularity of AJAX style development, it has suddenly become a hot new technology. Unfortunately, the most commonly used browser on the market is painfully slow at one of the most common tasks in programming -- string concatenation.

The good news is that although IE is slow when it comes to string concatenation, it is quite fast with array operations. With this in mind, I decided to write a simple StringBuilder class that pushes individual strings into an array and then uses the join method to produce the concatenated output string. In tests I have run with 5,000 strings, it is 117 times faster than the equivalent string concatenation using the s1 += s2 syntax. With 10,000 strings, it is an amazing 261 times faster!

Using the code

The StringBuilder class only provides four methods: a constructor, an append method, a clear method, and a toString method. You can add more properties and methods if you need them, but I chose to keep it as simple as possible for this article.

Here is the entire script that defines the StringBuilder class:

JavaScript
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}

The code is so simple and straightforward that it should be self-explanatory. Now here's an example of how to use it:

JavaScript
// create a StringBuilder
var sb = new StringBuilder();

// append some text
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
sb.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
sb.append("magna aliguam erat volutpat.");

// get the full string value
var s = sb.toString();

Again, so simple and straightforward it shouldn't require any further explanation. If you've ever used the StringBuilder in .NET, then you already know how to use this one.

If you download the demo project, you will find an HTML page that performs a side-by-side comparison of StringBuilder vs. string concatenation. You can use it to run your own tests to see the difference for yourself. On my machine, it takes IE over 14 seconds to concatenate 5,000 strings. The StringBuilder does it in 110 ms. With 10,000 strings, it takes IE a full minute to concatenate. The StringBuilder does it in 230 ms. More than a minute to less than a quarter of a second, that's a fairly significant improvement!

Conclusion

The whole purpose of pushing processing to the client is to provide a richer, more responsive user experience. That means, it's important to make sure the client-side code is as efficient as possible. I hope this article helps your client-side string building code really scream.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Epsilon
United States United States
IT professional with fifteen years experience designing and building software and web applications for local, national, and global organizations in a variety of industries including telecommunications, insurance, accounting, finance, not-for-profit, marketing, payment services, loyalty services, e-commerce, and e-business.

Comments and Discussions

 
QuestionThread Safety Issue Pin
carnegiea20-Aug-13 21:11
carnegiea20-Aug-13 21:11 
GeneralNot working in FireFox, Chrome and Safari, and runs slower on IE and Opera Pin
ynnorj2-Dec-09 18:05
ynnorj2-Dec-09 18:05 
GeneralRe: Not working in FireFox, Chrome and Safari, and runs slower on IE and Opera Pin
Erikerikerikerikerassa2-Jan-10 13:30
Erikerikerikerikerassa2-Jan-10 13:30 
GeneralRe: Not working in FireFox, Chrome and Safari, and runs slower on IE and Opera Pin
Kikoz6814-Jul-11 10:11
Kikoz6814-Jul-11 10:11 
QuestionStringBuilderPlus & Length = 1? Pin
AspDotNetDev7-Sep-09 21:32
protectorAspDotNetDev7-Sep-09 21:32 
AnswerRe: StringBuilderPlus & Length = 1? Pin
K.Collins8-Sep-09 5:38
K.Collins8-Sep-09 5:38 
GeneralIt is amazing Pin
arijit00729-Jan-09 0:39
arijit00729-Jan-09 0:39 
GeneralRe: It is amazing Pin
K.Collins29-Jan-09 5:04
K.Collins29-Jan-09 5:04 
GeneralCode Update (by player's edited version) Pin
player.7-Oct-08 20:20
player.7-Oct-08 20:20 
GeneralRe: Code Update (by player's edited version) Pin
K.Collins8-Oct-08 4:16
K.Collins8-Oct-08 4:16 
GeneralRe: Code Update (by player's edited version) Pin
player.29-Jul-09 21:55
player.29-Jul-09 21:55 
GeneralGoogle Chrome results Pin
I.Gl.23-Sep-08 7:48
I.Gl.23-Sep-08 7:48 
GeneralRe: Google Chrome results Pin
K.Collins8-Oct-08 4:09
K.Collins8-Oct-08 4:09 
GeneralThank you. Pin
arockj11-Jun-08 13:36
arockj11-Jun-08 13:36 
GeneralRe: Thank you. Pin
K.Collins12-Jun-08 5:53
K.Collins12-Jun-08 5:53 
GeneralEven Faster... Pin
LTSpeed21-Jun-07 3:46
LTSpeed21-Jun-07 3:46 
GeneralRe: Even Faster... Pin
essence19-Aug-14 11:36
essence19-Aug-14 11:36 
GeneralThanks Pin
SuperDuckZA_PS8-Apr-07 4:17
SuperDuckZA_PS8-Apr-07 4:17 
GeneralRe: Thanks Pin
K.Collins9-Apr-07 4:34
K.Collins9-Apr-07 4:34 
GeneralVery Good idea, with a small change! Pin
AjaxDino18-Jan-07 14:50
AjaxDino18-Jan-07 14:50 
GeneralRe: Very Good idea, with a small change! Pin
K.Collins19-Jan-07 4:52
K.Collins19-Jan-07 4:52 
QuestionDoesn't work in Firefox? Pin
DannSmith17-Sep-06 16:55
DannSmith17-Sep-06 16:55 
AnswerRe: Doesn't work in Firefox? Pin
Andrei Bozantan22-Sep-06 7:36
Andrei Bozantan22-Sep-06 7:36 
QuestionIs it from Atlas? Pin
Omari O.12-Dec-05 17:32
Omari O.12-Dec-05 17:32 
AnswerRe: Is it from Atlas? Pin
K.Collins13-Dec-05 4:00
K.Collins13-Dec-05 4:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.