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
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
Thanks for your interesting tip. keep it up……..
Comment by Md. Kausar Alam — July 30, 2009 @ 09:58