比较一下下面几种字符串拼接的方法:
// prepare a long array const arr = [] for (let i = 0; i < 10000; i++) { arr.push('item' + i) } function testByForLoop1 () { const tsStart = +new Date().valueOf() let html = '<ul>' for (let i = 0, len = arr.length; i < len; i++) { html += `<li>${arr[i]}</li>` } html += '</ul>' console.log('testByForLoop1: ' + (+new Date().valueOf() - tsStart)) } function testByForLoop2 () { const tsStart = +new Date().valueOf() let html = '<ul>' for (let i = 0, len = arr.length; i < len; i++) { html += '<li>' + arr[i] + '</li>' } html += '</ul>' console.log('testByForLoop2: ' + (+new Date().valueOf() - tsStart)) } function testByArrayJoinMethod () { const tsStart = +new Date().valueOf() let html = '<ul><li>' html += arr.join('</li><li>') html += '</li></ul>' console.log('testByArrayJoinMethod: ' + (+new Date().valueOf() - tsStart)) } testByForLoop1() testByForLoop2() testByArrayJoinMethod()
经过在Chrome浏览器多次尝试,总的来说,testByForLoop1方法(用了ES6字符串模板的for循环)耗时最长,testByForLoop2方法(没用ES6字符串模板的for循环)耗时其次,testByArrayJoinMethod方法(利用了数组的join方法)耗时最短,它们的耗时在数组长度越长时越是差异显著。尤其是testByArrayJoinMethod方法简直是效果拔群。下面是一个截图(截图里有个地方</ul></ul>是当时写错了,上面的代码里以纠正,截图就不换了。。):
处理小数据时怎么方便怎么来,因为在这种情况下可以认为上面三种方法的耗时是一样的,但是如果要处理很长的数据的话,能用数据join方法实现的话,效果不是一般的好。