java 代码优化
-
腾虎网络:2010-05-05 阅读数: 分享到:
一、字符串的连接
通常我们进行字符串连接是这样的:
var veryLongMessage =
‘This is a long string that due to our strict line length limit of’ +
maxCharsPerLine +
‘ characters per line must be wrapped. ‘ +
percentWhoDislike +
‘% of engineers dislike this rule. The line length limit is for ‘ +
‘ style purposes, but we don’t want it to have a performance impact.’ +
‘ So the question is how should we do the wrapping?’;
可以用如下的数字代替:
var veryLongMessage =
['This is a long string that due to our strict line length limit of',
maxCharsPerLine,
' characters per line must be wrapped. ',
percentWhoDislike,
'% of engineers dislike this rule. The line length limit is for ',
' style purposes, but we don't want it to have a performance impact.',
' So the question is how should we do the wrapping?'
].join();
二、通过助手函数生成字符串
通过把字符串生成器传递到函数中来构造一个长字符串,要避免临时的String结果,例如,假设函数buildMenuItemHtml_ 需要用文字串(literal)和变量来构造String,并在内部使用了String构造器.而不是如下方式使用:
var strBuilder = [];
for (var i = 0, length = menuItems.length; i