使用JMH测试日期格式化的性能

人们惯常的观念是,构造SimpleDateFormat对象是比较费时的,一般都会使用ThreadLocal来做一个性能优化。本文使用JMH对SimpleDateFormatApache Commons Lang FastDateFormatJava 8 DateTimeFormatter三者的性能做一个对比测试。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.henshao</groupId>
    <artifactId>date-format-JMH-test</artifactId>
    <version>1.0.0</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jmh.version>1.9.3</jmh.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>${jmh.version}</version>
        </dependency>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-generator-annprocess</artifactId>
            <version>${jmh.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.1</version>
        </dependency>
    </dependencies>
</project>

测试代码

package com.henshao.jmh;

import org.apache.commons.lang3.time.FastDateFormat;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class DateFormatTest {

    private static String sDateFormatString = "yyyy-MM-dd HH:mm:ss";

    private Date date = new Date();
    private LocalDateTime localDateTime = LocalDateTime.now();

    private static ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal();
    private static ThreadLocal<DateTimeFormatter> dateTimeFormatterThreadLocal = new ThreadLocal();

    @Setup
    public void setUp() {

        SimpleDateFormat sdf = new SimpleDateFormat(sDateFormatString);
        simpleDateFormatThreadLocal.set(sdf);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(sDateFormatString);
        dateTimeFormatterThreadLocal.set(dateTimeFormatter);
    }

    @Benchmark
    public void dateFormatJDK7() throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat(sDateFormatString);
        String dateString = sdf.format(date);
        if (dateString == null) {
            throw new Exception("format error");
        }
    }

    @Benchmark
    public void dateFormatThreadLocalJDK7() throws Exception {

        SimpleDateFormat sdf = simpleDateFormatThreadLocal.get();
        String dateString = sdf.format(date);
        if (dateString == null) {
            throw new Exception("format error");
        }
    }

    @Benchmark
    public void dateFormatJDK8() throws Exception {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(sDateFormatString);
        String dateString = localDateTime.format(dateTimeFormatter);
        if (dateString == null) {
            throw new Exception("format error");
        }
    }

    @Benchmark
    public void dateFormatThreadLocalJDK8() throws Exception {

        DateTimeFormatter dateTimeFormatter = dateTimeFormatterThreadLocal.get();
        String dateString = localDateTime.format(dateTimeFormatter);
        if (dateString == null) {
            throw new Exception("format error");
        }
    }

    @Benchmark
    public void fastDateFormat() throws Exception {

        FastDateFormat fastDateFormat = FastDateFormat.getInstance(sDateFormatString);
        String dateString = fastDateFormat.format(date);
        if (dateString == null) {
            throw new Exception("format error");
        }
    }

    public static void main(String[] args) throws RunnerException {

        Options opt = new OptionsBuilder()
                .include(DateFormatTest.class.getSimpleName())
                .forks(1)
                .warmupIterations(5)
                .measurementIterations(5)
                .build();

        new Runner(opt).run();
    }
}

时间格式化其实并不耗时,就算每次都要创建SimpleDateFormat对象,耗时也是微秒级别。FastDateFormat性能最好,DateTimeFormatter性能也很好,二者比SimpleDateFormat的性能都有巨大的提升。但是SimpleDateFormat使用ThreadLocal之后,差异就很小了。DateTimeFormatterthread-safe and immutable的,其实是不需要放到ThreadLocal里面的。

# JMH 1.9.3 (released 1337 days ago, please consider updating!)
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/jre/bin/java
# VM options: -Dvisualvm.id=213500268222641 -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=65096:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.henshao.jmh.DateFormatTest.dateFormatJDK7

# Run progress: 0.00% complete, ETA 00:00:50
# Fork: 1 of 1
# Warmup Iteration   1: 2.670 us/op
# Warmup Iteration   2: 1.477 us/op
# Warmup Iteration   3: 1.386 us/op
# Warmup Iteration   4: 0.985 us/op
# Warmup Iteration   5: 0.988 us/op
Iteration   1: 0.969 us/op
Iteration   2: 0.961 us/op
Iteration   3: 0.981 us/op
Iteration   4: 0.977 us/op
Iteration   5: 0.977 us/op


Result "dateFormatJDK7":
  0.973 ±(99.9%) 0.031 us/op [Average]
  (min, avg, max) = (0.961, 0.973, 0.981), stdev = 0.008
  CI (99.9%): [0.942, 1.004] (assumes normal distribution)


# JMH 1.9.3 (released 1337 days ago, please consider updating!)
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/jre/bin/java
# VM options: -Dvisualvm.id=213500268222641 -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=65096:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.henshao.jmh.DateFormatTest.dateFormatJDK8

# Run progress: 20.00% complete, ETA 00:01:03
# Fork: 1 of 1
# Warmup Iteration   1: 0.674 us/op
# Warmup Iteration   2: 0.633 us/op
# Warmup Iteration   3: 0.494 us/op
# Warmup Iteration   4: 0.474 us/op
# Warmup Iteration   5: 0.475 us/op
Iteration   1: 0.477 us/op
Iteration   2: 0.473 us/op
Iteration   3: 0.477 us/op
Iteration   4: 0.478 us/op
Iteration   5: 0.480 us/op


Result "dateFormatJDK8":
  0.477 ±(99.9%) 0.010 us/op [Average]
  (min, avg, max) = (0.473, 0.477, 0.480), stdev = 0.003
  CI (99.9%): [0.467, 0.487] (assumes normal distribution)


# JMH 1.9.3 (released 1337 days ago, please consider updating!)
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/jre/bin/java
# VM options: -Dvisualvm.id=213500268222641 -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=65096:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.henshao.jmh.DateFormatTest.dateFormatThreadLocalJDK7

# Run progress: 40.00% complete, ETA 00:00:47
# Fork: 1 of 1
# Warmup Iteration   1: 0.435 us/op
# Warmup Iteration   2: 0.357 us/op
# Warmup Iteration   3: 0.277 us/op
# Warmup Iteration   4: 0.282 us/op
# Warmup Iteration   5: 0.276 us/op
Iteration   1: 0.283 us/op
Iteration   2: 0.283 us/op
Iteration   3: 0.281 us/op
Iteration   4: 0.280 us/op
Iteration   5: 0.281 us/op

Result "dateFormatThreadLocalJDK7":
  0.282 ±(99.9%) 0.005 us/op [Average]
  (min, avg, max) = (0.280, 0.282, 0.283), stdev = 0.001
  CI (99.9%): [0.277, 0.287] (assumes normal distribution)

# JMH 1.9.3 (released 1337 days ago, please consider updating!)
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/jre/bin/java
# VM options: -Dvisualvm.id=213500268222641 -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=65096:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.henshao.jmh.DateFormatTest.dateFormatThreadLocalJDK8

# Run progress: 60.00% complete, ETA 00:00:31
# Fork: 1 of 1
# Warmup Iteration   1: 0.298 us/op
# Warmup Iteration   2: 0.277 us/op
# Warmup Iteration   3: 0.279 us/op
# Warmup Iteration   4: 0.244 us/op
# Warmup Iteration   5: 0.243 us/op
Iteration   1: 0.283 us/op
Iteration   2: 0.320 us/op
Iteration   3: 0.312 us/op
Iteration   4: 0.283 us/op
Iteration   5: 0.242 us/op


Result "dateFormatThreadLocalJDK8":
  0.288 ±(99.9%) 0.119 us/op [Average]
  (min, avg, max) = (0.242, 0.288, 0.320), stdev = 0.031
  CI (99.9%): [0.170, 0.407] (assumes normal distribution)


# JMH 1.9.3 (released 1337 days ago, please consider updating!)
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/jre/bin/java
# VM options: -Dvisualvm.id=213500268222641 -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=65096:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.henshao.jmh.DateFormatTest.fastDateFormat

# Run progress: 80.00% complete, ETA 00:00:15
# Fork: 1 of 1
# Warmup Iteration   1: 0.634 us/op
# Warmup Iteration   2: 0.511 us/op
# Warmup Iteration   3: 0.561 us/op
# Warmup Iteration   4: 0.402 us/op
# Warmup Iteration   5: 0.464 us/op
Iteration   1: 0.473 us/op
Iteration   2: 0.520 us/op
Iteration   3: 0.401 us/op
Iteration   4: 0.421 us/op
Iteration   5: 0.392 us/op

Result "fastDateFormat":
  0.441 ±(99.9%) 0.208 us/op [Average]
  (min, avg, max) = (0.392, 0.441, 0.520), stdev = 0.054
  CI (99.9%): [0.233, 0.650] (assumes normal distribution)

# Run complete. Total time: 00:01:19

Benchmark                                 Mode  Cnt  Score   Error  Units
DateFormatTest.dateFormatJDK7             avgt    5  0.973 ± 0.031  us/op
DateFormatTest.dateFormatJDK8             avgt    5  0.477 ± 0.010  us/op
DateFormatTest.dateFormatThreadLocalJDK7  avgt    5  0.282 ± 0.005  us/op
DateFormatTest.dateFormatThreadLocalJDK8  avgt    5  0.288 ± 0.119  us/op
DateFormatTest.fastDateFormat             avgt    5  0.441 ± 0.208  us/op

参考文章:Java 并发编程笔记:JMH 性能测试框架

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,294评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,780评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,001评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,593评论 1 289
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,687评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,679评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,667评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,426评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,872评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,180评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,346评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,019评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,658评论 3 323
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,268评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,495评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,275评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,207评论 2 352