最近研究netty源码,有一段代码,引起我对Integer.toString性能的关注:
先上netty源码片段:
private static final String[] INTEGERS = {
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "12", "13", "14", "15",
};
public static String toString(int value) {
if (value >= 0 && value < INTEGERS.length) {
return INTEGERS[value];
} else {
return Integer.toString(value);
}
}
这个toString方法是netty将handler对象放到Map中,在获取Map的key时调用的。作者定义了16个下标,超过16则调用Integer.toString方法获取下标。
这就有一个问题了,Integer.toString到底比直接去取定义在数组的字符串慢多少呢,看下面的测试代码:
final String[] str = { new String("1"), new String("2"), new String("3"), new String("4"), new String("5"),
new String("6"), new String("7"), new String("8"), new String("9"), new String("10"), new String("11") };
Date start = new Date();
long startTime = start.getTime();
for (int i = 0; i < 1000000; i++) {
for (int j = 0; j < 11; j++) {
String test = str[j];
}
}
Date end = new Date();
long endTime = end.getTime();
System.out.println("数组所需时间:" + (endTime - startTime));
Date start1 = new Date();
long startTime1 = start1.getTime();
for (int i = 0; i < 1000000; i++) {
for (int j = 0; j < 11; j++) {
String test = Integer.toString(j);
}
}
Date end1 = new Date();
long endTime1 = end1.getTime();
System.out.println("ToString所需时间:" + (endTime1 - startTime1));
数组所需时间:16ms
ToString所需时间:328ms
测试结果很明显了,到数组里面取比调用Integer.toString方法要快很多。
为啥快呢?
个人认为:1,由于拆箱装箱的原理,获取字符串的内存区域不同。
2,可以看看Integer.toString源码:
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(0, size, buf);
}
当然,在很多系统,这么点时间根本就算不了什么。但是如果碰到netty这种使用场景,可以做一些优化。哈哈.
可能有没有想到的地方,希望大家补充。
本文通过对比测试,发现直接从数组获取字符串比调用Integer.toString方法快近20倍。深入分析了其背后的原理,并给出了适用于Netty等高性能场景的优化建议。
1357

被折叠的 条评论
为什么被折叠?



