感受大量构造异常带来的性能影响:
package com;
/**
* 异常也会影响性能(在非常高的请求频率下)
*/
public class ExceptionPerformance {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
testParseWithException(100000);
System.out.println(System.currentTimeMillis() - t1);
t1 = System.currentTimeMillis();
testParse(100000);
System.out.println(System.currentTimeMillis() - t1);
}
/**
* just: 66 ms
*/
private static void testParse(long size){
for (int i = 0; i < size; i++) {
parse(i + "");
parse(i + "");
}
}
/**
* 1497 ms
*/
private static void testParseWithException(long size){
for (int i = 0; i < size; i++) {
parse(i + "%");
parse(i + "%");
}
}
public static double parse(String data) {
try {
return Integer.parseInt(data);
} catch (Exception e) {
try {
return Double.parseDouble(data);
} catch (Exception e1) {
try {
return Integer.parseInt(data.replaceAll("%", ""));
} catch (Exception e3) {
return 0;
}
}
}
}
}