SimpleDateFormat性能优化

本文探讨了在高频率日志记录场景下,使用ThreadLocal优化SimpleDateFormat性能的方法。通过重写initialValue方法和调用set()方法,避免了频繁创建对象导致的性能损耗。

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


后台数据发现APP出现一个ANR。追踪发现是日志库SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);出现的。
由于APP一旦启动就会生成大量的日志,每条日志都有日期,该代码会创建很多对象。对于一般需求改性能可以忽略,但是对于频繁创建日志来说,性能有较高要求。

使用ThreadLocal

ThreadLocal是线程的局部变量,是每一个线程所单独持有的,其他线程不能对其进行访问,由于在每个线程中都创建了副本,所以要考虑它对资源的消耗。

1、重写initialValue方法

public class DateUtil {

        private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {

            protected DateFormat initialValue() {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
        };

        public static Date parse(String dateStr) throws ParseException {
            return threadLocal.get().parse(dateStr);
        }

        public static String format(Date date) {
            return threadLocal.get().format(date);
        }
    }

2、调用set()方法赋值

public class DateUtil {

        private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();

        public static DateFormat getDateFormat()
        {
            DateFormat df = threadLocal.get();
            if(df==null){
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                threadLocal.set(df);
            }
            return df;
        }

        public static String formatDate(Date date) throws ParseException {
            return getDateFormat().format(date);
        }

        public static Date parse(String strDate) throws ParseException {
            return getDateFormat().parse(strDate);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值