It is Bip Bip Bipool

May 23, 2008

String Concate In JavaScript

Filed under: javascript — bipool @ 18:30

In JavaScript , String concatenation is too much slow. If you have some long string and need to concate in a loop.  It will take long  time to execute the process. If your loop iteration is like 2000 times and your string like 100 characters long, then it might take 7-8 seconds to execute. Thats a real fact for optimization. JavaScript actually store data in many places when concate  the string.

If you do following way then process time will reduce significantly. If you store every string in an array and then join the string using array.join(“”) function , it will reduce time. I got it reduces 70-75% time of previous one .

Advertisement

2 Comments »

  1. That’s because strings are immutable, while arrays aren’t.

    String concatenation is expensive if repeated because every concatenation operation reallocates the entire string (so far) in memory and copies it.

    Hence the behaviour in a loop M times with strings of length N is N * (N/2) * M, or O(N^2 * M).

    With your suggested method, the behaviour is N + N * M, or O(N * M). Much better.

    (So the speedup will be better and better as the number of iterations grows).

    So, a good tip. Also applicable in many other languages such as Python, Java, C#, etc.

    Comment by Matt Giuca — May 24, 2008 @ 14:17

  2. Thanks for your interesting tip. keep it up……..

    Comment by Md. Kausar Alam — July 30, 2009 @ 09:58


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Banana Smoothie. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.