人们惯常的观念是,构造SimpleDateFormat
对象是比较费时的,一般都会使用ThreadLocal来做一个性能优化。本文使用JMH对SimpleDateFormat
、Apache Commons Lang FastDateFormat
、Java 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
之后,差异就很小了。DateTimeFormatter
是thread-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