In this series of articles I will try to provide some guidelines, tips and tricks about JavaScript performance.The first article will handle string concatenation, methods and performance guidelines which will make your JavaScript code better, allow it to run faster and provide smoother user experience.
The problem
Most JavaScript developers use the easy String manipulation possibilities which JavaScript offers, that is combining string with the + operator.
var str = "Hello" + " World";
While this is very readable and convenient method to handle small string operations, when using it to handle many strings (like building the page dynamically) the performance is severely damaged.
Worry no more! A solution is in hand...
The solution
The Array object join method provides us a way to join all the elements of an array into a single string separated by a specified string separator.
If we will assign each string as an element in the Array and will join all the elements with an empty char as our separator we will have the same result as using the + operator. This method is very similar to Java's StringBuffer object.
var buffer = new Array();
buffer[buffer.length] = "Hello";
buffer[buffer.length] = " World";
buffer.join("");
The benefit
The benefit of using Array.join to combine strings is pure performance issue.
In order to see how much the use of Array.join can benefit us let's do some benchmarking test with both methods.
We will use a simple code that combine some strings 10,000 times with both methods.
Here are the results:
Regular string concatenation:
IE 6 - Avarage runtime 646ms (Max value was: 810ms, Min value was: 460ms)
FireFox 1.5B1 - Avarage runtime 26ms (Max value was: 47ms, Min value was: 15ms)
Array.join:
IE 6 - Avarage runtime 26ms (Max value was: 32ms, Min value was: 15ms)
FireFox 1.5B1 - Avarage runtime 20ms (Max value was: 31ms, Min value was: 15ms)
The results are impressive Array.join show 2484% (!!!) improvement over regular strings in IE. While in FF the differences are insignificant which means the guys in Mozzila know their job :-)
Conclusion
Use the Array.join to boost up performance in you JavaScript web applications and provide your user more fluent and smooth user experience.
Uzi Refaeli has sinced written about articles on various topics from Education Toys, Site Promotion. Uzi Refaeli is the CTO of Comet Information Systems which specialize with and. Uzi Refaeli's top article generates over 880 views. to your Favourites.
5.8 Ghz Digital Phones Water sports of all kinds are available in the emirate from sailing to jet skis and everything else imaginable. Fujairah also hosts the Power Boat Racing World Championship every October