除了if (x = 0)
那确实应该是if (i % 2 === 0)
,您确实应该通过使用 Array.join() 方法而不是连接字符串来提高性能。这将产生类似的效果字符串生成器 http://www.yoda.arachsys.com/csharp/stringbuilder.html在 C# 或 Java 中。
例如:
function showTableData()
{
var tableArray;
var theHTML = [];
theHTML.push('<table id="mytable" cellspacing="0">',
'<tr>',
'<th scope="col" abbr="Configurations" class="nobg">Part Number</th>',
'<th scope="col" abbr="Dual 1.8">Msrp Price</th>',
'<th scope="col" abbr="Dual 2">blahs Price</th>',
'<th scope="col" abbr="Dual 2.5">Low Price</th>',
'</tr>');
for (var i = 0; i < 7032; i++)
{
if (i % 2 == 0)
{
theHTML.push('<tr>',
'<th scope="row" class="spec">', partNum[i], '</th>',
'<td>', Msrp[i], '</td>',
'<td>', blah[i], '</td>',
'<td>', blahs[i], '</td>',
'</tr>');
} else {
theHTML.push('<tr>',
'<th scope="row" class="specalt">', partNum[i], '</th>',
'<td class="alt">', Msrp[i], '</td>',
'<td class="alt">', blah[i], '</td>',
'<td class="alt">', blahs[i], '</td>',
'</tr>');
}
}
theHTML.push('</table>');
$('#example').append(theHTML.join(''));
}
</script>
<div id="example">
</div>
附加字符串的原因'my' + ' appended' + ' string'
比连接字符串慢['my', ' joined', ' string'].join('')
是因为JavaScript 字符串是不可变的 https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-js因此,在前一个示例中,每次连接 2 个字符串时都会创建第三个字符串,与向数组中添加新条目相比,这是一个非常昂贵的操作。
另请参阅JavaScript StringBuilder 项目 http://www.codeproject.com/KB/scripting/stringbuilder.aspx使用 Array.push() 和 Array.join() 相同的原理构建。
该项目在 IE 中进行 10,000 次串联的性能改进从 1 分钟多降至 0.23 秒。
UPDATE:添加了对 Array.join() 的额外调用来替换 for 循环内的字符串连接,这是为了进一步提高客户端渲染速度。 + 添加了更好的 StringBuilder 链接。
进一步更新:Hemlock 添加了建议:
- 通过定义删除了全局范围变量的使用
var i = 0
在for循环中
- 使用 Array.push() 的多个参数一次推送多个字符串。