Fastest way to build an HTML string

You have a massive array of items that needs to be transformed into an HTML list without causing the user any grief. There are a couple common ways of doing this:
Note: I’m not even going to bother covering direct DOM manipulation for every list item because that’d be plain stupid!
#1 - Step-by-step string concat
Not the slowest method that exists but probably the most common:


var arr = ['item 1', 'item 2', 'item 3', ...],
list = '';

for (var i = 0, l = arr.length; i < l; i++) {
list += '<li>' + arr[i] + '</li>';
}

list = '<ul>' + list + '</ul>';


Don’t use this. It’s inefficient, slow and ugly!
#2 - Step-by-step array pushing

var arr = ['item 1', 'item 2', 'item 3', ...],
list = [];

for (var i = 0, l = arr.length; i < l; i++) {
list[list.length] = '<li>' + arr[i] + '</li>';
}

list = '<ul>' + list.join('') + '</ul>';


Slightly faster than string concatenation but still not perfect…
#3 - The holy grail!

var arr = ['item 1', 'item 2', 'item 3', ...];

var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!
Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
Browser benchmarks
Due to a request and my own curiousity I’ve conducted a quick benchmarking test. Each method was tested with a 130-item array, the length of each item varied so any optimizations on the browser’s part would not be effective. Each method was tested 1000 times; the results below show how long each browser took to complete each method 1000 times:
“String concat” (ms) “Array pushing” (ms) “Native join()” (ms)


Firefox 3 147 148 65
Opera 9 172 125 78
IE 7 500 2297 79
Chrome 2 63 88 72
Safari 4b 146 141 60
Averages 205 559 70

Surprisingly, string concatenation came out much faster than “array pushing” on average. It seems IE7 optimizes for lengthy string operations but doesn’t care much for arrays. Also, Google Chrome performed oddly; the “string concatenation” method was quicker than the “native join()”… I’m not too sure what’s going on there! Anyway, the results were mostly predictable, and, of course, “native join()” came out on top!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值