最近自己寫程序的時候,想提高程序的性能。
一個基本的想法是:減少對象的創建。由於我的程序中要大量使用整數操作,包括 Integer.toString() 、Integer.toHexString() 等等。理論上,每次調用這些函數的時候都會解析整數,並生成字符串,所以我自己寫了個類來緩存結果,第二次調用的時候就不用再計算了。
以下代碼發佈在公共領域(Public Domain)下,你可以自由地使用它們。
/**
* Integer utils, cached many results of toString/toHexString to get better performance<p>
* Java 1.4 compatible
*
* @author henix[http://shell-picker.iteye.com]
*/
public class IntegerUtils {
static final int MAX_CACHED = 2048;
private static Integer[] cache = new Integer[MAX_CACHED];
private static String[] cachedStrings = new String[MAX_CACHED];
private static String[] cachedHexStrings = new String[MAX_CACHED];
/**
* Implement the same logic as Integer.valueOf(int) in Java 1.5.
*
* @param i
* @return
*/
public static Integer getInteger(int i) {
if (i >= 0 && i < MAX_CACHED) {
synchronized (cache) {
if (cache[i] == null) {
cache[i] = new Integer(i);
}
}
return cache[i];
} else {
return new Integer(i);
}
}
public static String toString(int i) {
if (i >= 0 && i < MAX_CACHED) {
synchronized (cachedStrings) {
if (cachedStrings[i] == null) {
cachedStrings[i] = Integer.toString(i);
}
}
return cachedStrings[i];
} else {
return Integer.toString(i);
}
}
public static String toHexString(int i) {
if (i >= 0 && i < MAX_CACHED) {
synchronized (cachedHexStrings) {
if (cachedHexStrings[i] == null) {
cachedHexStrings[i] = Integer.toHexString(i);
}
}
return cachedHexStrings[i];
} else {
return Integer.toHexString(i);
}
}
/**
* parseInt that never throws exceptions
*
* @param str
* @return
*/
public static int parseInt(String str) {
try {
return Integer.parseInt(str);
} catch (Exception e) {
return 0;
}
}
public static int parseInt(String str, int radix) {
try {
return Integer.parseInt(str, radix);
} catch (Exception e) {
return 0;
}
}
}