summary
Work summary, technical summary and guide.
一、代码实现细节
1、避免频繁进行装拆箱,十分影响性能,特别是在循环中(在下面两个示例中仅仅修改了数据类型,就达到了性能上的20倍提升):
// 一般实现
public static void main(String[] args) {
long t = System.currentTimeMillis();
Long sum = 0L;
for (Long i = 0L; i < 1000000000L; i = i + 1) {
sum = sum + i;
}
System.out.println("processing time: " + (System.currentTimeMillis() - t) + " ms");
}
processing time: 5142 ms
// 更好的实现
public static void main(String[] args) {
long t = System.currentTimeMillis();
long sum = 0L;
for (long i = 0L; i < 1000000000L; i = i + 1) {
sum = sum + i;
}
System.out.println("processing time: " + (System.currentTimeMillis() - t) + " ms");
}
processing time: 247 ms
此外:字符串转基本类型时应使用parseXXX(String str)
,转包装类型时才使用valueOf(String str)
// 一般实现
Integer reserve = defaultReserve;
if (StringUtils.isNumeric(params.getReserve())) {
reserve = Integer.valueOf(params.getReserve()) + 1;
}
// 更好的实现
Integer reserve = defaultReserve;
if (StringUtils.isNumeric(params.getReserve())) {
reserve = Integer.parseInt(params.getReserve()) + 1;
}
2、匿名内部类修改为lambda
表达式,提升性能,简化代码(示例场景:文件名前缀和后缀过滤):
// 一般实现
String[] fileNames = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("wsf") && name.endsWith(".xml");
}
});
// 更好的实现
String[] fileName = file.list((dir, name) -> name.startsWith("wsf") && name.endsWith(".xml"));
3、优先使用Java 7
的新语法try-with-resources
来关闭AutoCloseable
的资源:
// 一般实现
InputStream in = new ZipInputStream(new BufferedInputStream(inputStream));
try {
// do something
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
// 更好的实现
try (InputStream in = new ZipInputStream(new BufferedInputStream(inputStream))) {
// do something
}
4、使用Java 8的Optional
来简化连续调用,并消除NullPointerException
:
// 一般实现,示例场景:获取元素(Element)的子元素(Child Attribute)的属性(Attribute)的值(Value)
public static String getAttributeValue(Element root, String elementName, String attributeName) {
if(root == null) {
return "";
}
Element child = root.element(elementName);
if(child == null) {
return "";
}
Attribute attribute = child.attribute(attributeName);
if(attribute == null) {
return "";
}
String value = attribute.getValue();
if (value == null){
return "";
}</