IntegerUtils :一个关于整数操作的工具类

本文介绍了一种通过缓存整数转换为字符串的结果来提高程序性能的方法,避免了重复计算,适用于频繁进行整数到字符串转换的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近自己写程序的时候,想提高程序的性能。

 

一个基本的想法是:减少对象的创建。由于我的程序中要大量使用整数操作,包括 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;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值