首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >性能有点不错的时间工具类

性能有点不错的时间工具类

作者头像
阿超
发布2022-08-16 18:54:47
发布2022-08-16 18:54:47
4730
举报
文章被收录于专栏:快乐阿超快乐阿超

人们宁愿去关心一个蹩脚电影演员的吃喝拉撒和鸡毛蒜皮,而不愿了解一个普通人波涛汹涌的内心世界。——路遥《平凡的世界》

首先是依赖lang3

代码语言:javascript
复制
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

然后是工具类

代码语言:javascript
复制
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;
        }
    }
}

实际测试

代码语言:javascript
复制
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");
}

输出时间测试结果

而且这个耗时是会越来越短的

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-01-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档