SimpleDateFormat的性能

    在论坛上闲逛无意间发现一条说SimpleDateFormat性能的帖子。之前并未关心过,也并不知道。读了下来才了解他引述的是Tim Cull发现SimpledataFormat创建实例时内存开销很大。这让我联想到了公司项目中资产设备运行不久就老是报内存溢出的错误。因为项目还未有过性能测试,因此我先猜测可能与这个有关,因为在项目中我们也大量使用了此类。因为没有安装性能测试工具,无法证实次论断的真实性,现在这里信之,后面做测试。经查找找到了Tim Cull的原文,贴在下面,他给出了一种解决方案,可供参考。

    SimpleDateFormat: Performance Pig
    BY TIM CULL

    Just yesterday I came across this problem “in the wild” for the third time in my career so far: an application with performance problems creating tons of java.text.SimpleDateFormat instances. So, I have to get this out there: creating a new instance of SimpleDateFormat is incredibly expensive and should be minimized. In the case that prompted this post, I was using JProfiler to profile this code that parses a CSV file and discovered that 50% of the time it took to suck in the file and make 55,000 objects out of it was spent solely in the constructor of SimpleDateFormat. It created and then threw away a new one every time it had to parse a date. Whew!
    “Great,” you think, “I’ll just create one, static instance, slap it in a field in a DateUtils helper class and life will be good.”
    Well, more precisely, life will be good about 97% of the time. A few days after you roll that code into production you’ll discover the second cool fact that’s good to know: SimpleDateFormat is not thread safe. Your code will work just fine most of the time and all of your regression tests will probably pass, but once your system gets under a production load you’ll see the occasional exception.
“Fine,” you think, “I’ll just slap a ’synchronized’ around my use of that one, static instance.”
Ok, fine, you could do that and you’d be more or less ok, but the problem is that you’ve now taken a very common operation (date formatting and parsing) and crammed all of your otherwise-lovely, super-parallel application through a single pipe to get it done.
    What would be better is to use a ThreadLocal variable so you can have your cake and eat it, too:

public class DateUtils {

    public static final String MY_STANDARD_DATE_FORMAT = "yyyyMMdd";

    public static java.util.Date parseDate(String dateString) throws ParseException {
        return getFormat().parse(dateString);
    }

    private static ThreadLocal format = new ThreadLocal(){
        protected synchronized Object initialValue() {
            return new java.text.SimpleDateFormat(MY_STANDARD_DATE_FORMAT);
        }
    }

    private static DateFormat getFormat(){
        return (DateFormat) format.get();
    }
}

I hope this code works because I wrote it on the fly and haven’t tried to run it, but you get the point.

文章地址: http://www.thedwick.com/blog/2008/04/simpledateformat-performance-pig/

Tim Cull 博客: http://www.thedwick.com/blog/

Tim Cull 文章: http://www.infoq.com/cn/articles/java_legacy_systems

在网上查找了几篇相关文章:

http://www.iteye.com/topic/757641

http://hi.baidu.com/china8jie/blog/item/9452b50fa9bec0e3aa645735.html

你可能感兴趣的:(thread,Blog,performance)