人们宁愿去关心一个蹩脚电影演员的吃喝拉撒和鸡毛蒜皮,而不愿了解一个普通人波涛汹涌的内心世界。——路遥《平凡的世界》
首先是依赖lang3
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.11</version> </dependency>
然后是工具类
package com.ruben.utils; import org.apache.commons.lang3.time.FastDateFormat; import java.util.concurrent.atomic.AtomicReference; /** * DateFormat.format()消耗较大,如果时间戳是递增的,而且同一单位内有多次format(),使用用本类减少重复调用. * <p> * From Log4j2 DatePatternConverter,进行了优化,根据输出格式是否毫秒级,决定缓存在秒级还是毫秒级. * * @author calvin */ public class CachingDateFormatter { private final FastDateFormat fastDateFormat; private final AtomicReference<CachedTime> cachedTime; private final boolean onSecond;// 根据时间格式,决定缓存在 public CachingDateFormatter(String pattern) { this(FastDateFormat.getInstance(pattern)); } public CachingDateFormatter(FastDateFormat fastDateFormat) { this.fastDateFormat = fastDateFormat; onSecond = fastDateFormat.getPattern().indexOf("SSS") == -1; long current = System.currentTimeMillis(); this.cachedTime = new AtomicReference<CachedTime>(new CachedTime(current, fastDateFormat.format(current))); } public String format(final long timestampMillis) { CachedTime cached = cachedTime.get(); long timestamp = onSecond ? timestampMillis / 1000 : timestampMillis; if (timestamp != cached.timestamp) { final CachedTime newCachedTime = new CachedTime(timestamp, fastDateFormat.format(timestampMillis)); if (cachedTime.compareAndSet(cached, newCachedTime)) { cached = newCachedTime; } else { cached = cachedTime.get(); } } return cached.formatted; } static final class CachedTime { public long timestamp; public String formatted; public CachedTime(final long timestamp, String formatted) { this.timestamp = timestamp; this.formatted = formatted; } } }
实际测试
private static final String PATTERN = "yyyy-MM-dd HH:mm:SSS"; public static void main(String[] args) { // 原始方式 long dateTimeStart = System.nanoTime(); Stream.generate(() -> LocalDateTime.now().format(DateTimeFormatter.ofPattern(PATTERN))).limit(10000).collect(Collectors.toList()); long dateTimeEnd = System.nanoTime(); System.out.println((dateTimeEnd - dateTimeStart) / (1000.0 * 1000.0) + "ms"); // 工具类,手动获取实例 long start = System.nanoTime(); Stream.generate(() -> new CachingDateFormatter(FastDateFormat.getInstance(PATTERN)).format(System.currentTimeMillis())).limit(10000).collect(Collectors.toList()); long end = System.nanoTime(); System.out.println((end - start) / (1000.0 * 1000.0) + "ms"); // 工具类,自动获取实例 long patternStart = System.nanoTime(); Stream.generate(() -> new CachingDateFormatter(PATTERN).format(System.currentTimeMillis())).limit(10000).collect(Collectors.toList()); long patternEnd = System.nanoTime(); System.out.println((patternEnd - patternStart) / (1000.0 * 1000.0) + "ms"); }
输出时间测试结果
而且这个耗时是会越来越短的
