This section is unique because we often use concatenation techniques
for code readability and organisation benefits in addition to business
logic purposes. In other words, we tend to intentionally sacrifice
application performance in favour of prettier code. I’ll stick to this
notion to demonstrate the speed differences. Common concatenation
principles include:
How many times have you seen something like this bit of code:
Let’s rewrite that statement, persist the prettiness, and increase the performance:
foo = foo + bar; foo += bar;The first one will turn out to be faster in all browsers, by a small margin (only Safari 5 will double the performance). That’s good to know, sure, but there’s more to come.
How many times have you seen something like this bit of code:
Ext.create('MyView', { tpl: [ '<div class="heading">', '<div class="firstname">', '{firstname}', '</div>', '<div class="lastname">', '{lastname}', '</div>', '</div>' ].join() });I created an array of strings and used
Array.prototype.join
to combine them into one. Of course, it’s much prettier than combining with a + sign, and the code is more readable, too.[].join()
is, naturally, slower in all browsers but
Chrome. Just as the evaluation test above, Chrome is able to employ
advanced caching techniques to deliver faster results for repeated
actions. In other words, in real life [].join()
will always be slower.Let’s rewrite that statement, persist the prettiness, and increase the performance:
Ext.create('MyView', { tpl: ''.concat( '<div class="heading">', '<div class="firstname">', '{firstname}', '</div>', '<div class="lastname">', '{lastname}', '</div>', '</div>' ) });Instead of creating a new array, filling it up with strings and then joining it, I simply created an empty string and used
String.prototype.concat
method to append arguments to it. Visually it doesn’t make a huge
difference, the code is as pretty as it was. However, the latter
performs significantly faster than any other form of concatenation.
0 comments:
Post a Comment