問題
用SonarQube做代碼掃描,發現Boxing/Unboxing to parse a primitive,tag標記得是性能問題。
驗證
Long.valueOf(str)源碼
public static Long valueOf(String s) throws NumberFormatException
{
return Long.valueOf(parseLong(s, 10));
}
paserLong()
public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
再看Long.parseLong(str) public static long parseLong(String s) throws NumberFormatException {
return parseLong(s, 10);
}
parseLong 和Long.valueOf(str) 中調用的是一致的。
所以差別,就在於Long.valueOf(long),
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
也就是將long基本類型加了一個封裝類。
做了一個小測試,分別用Long.valueOf和Long.parseLong()來轉換,結果時間都相等
public static void main(String[] args) throws Exception{
Long start= System.currentTimeMillis();
Long t=Long.valueOf("1222222222222222223");
Long end= System.currentTimeMillis();
System.out.println("test1 "+(end-start));
Long start1= System.currentTimeMillis();
long t1=Long.parseLong("1222222222222222223");
Long end1= System.currentTimeMillis();
System.out.println("test2 "+(end1-start1));
}
結果test1 0
test2 0
看樣子,兩個沒有什麼差別
結論
通過自己的方法驗證,其實兩個字符串轉換,性能沒有差別。
以上都是個人愚見!