java 代碼優(yōu)化
-
騰虎網(wǎng)絡(luò):2010-05-05 閱讀數(shù): 分享到:
一、字符串的連接
通常我們進(jìn)行字符串連接是這樣的:
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?’;
可以用如下的數(shù)字代替:
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();
二、通過助手函數(shù)生成字符串
通過把字符串生成器傳遞到函數(shù)中來構(gòu)造一個(gè)長(zhǎng)字符串,要避免臨時(shí)的String結(jié)果,例如,假設(shè)函數(shù)buildMenuItemHtml_ 需要用文字串(literal)和變量來構(gòu)造String,并在內(nèi)部使用了String構(gòu)造器.而不是如下方式使用:
var strBuilder = [];
for (var i = 0, length = menuItems.length; i