java - 就内存和性能而言,在 Java 中每秒打印格式化日期+时间的最有效方法是什么?

标签 java performance datetime datetime-format

我能想到的有两种选择:

选项 1:

public class TimestampFormatter {

    private static SimpleDateFormat dateFormatter = 
            new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    private static Date date = new Date();

    public static String get() {
        date.setTime(System.currentTimeMillis());
        return dateFormatter.format(date);
    }
}

选项 2:

public class TimestampFormatter {

    private static SimpleDateFormat dateFormatter = 
            new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    public static String get() {
        return dateFormatter.format(new Date());
    }
}

然后使用这个循环每秒打印格式化的日期+时间:

new Thread(() -> {
            while (true) {
                System.out.println(TimestampFormatter.get());
                Sleep.millis(1000);
            }
        }).start();

我认为第一个选项是这里两个选项中最好的,但是有人能想到更好的方法吗?

最佳答案

第二个选项可能比第一个更有效率(或者第一个infinitesimally更好 - 我怀疑你能衡量任何差异). 无论如何我更喜欢更新 java.time.format.DateTimeFormatterjava.time.LocalDateTime在长期弃用的 SimpleDateFormatDate 类上。此外,安排重复的 Timer 会更有效率。而不是使用 while 循环和重复 sleep 调用。类似的东西,

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
TimerTask task = new TimerTask() {
    public void run() {
        System.out.println(dtf.format(LocalDateTime.now()));
    }
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, TimeUnit.SECONDS.toMillis(0), 
        TimeUnit.SECONDS.toMillis(1));

关于java - 就内存和性能而言,在 Java 中每秒打印格式化日期+时间的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59233384/

相关文章:

java - 如何添加包级别注释或编辑 package-info.java?

java - jdk socket实现了哪些协议(protocol)

java - 用Java写入ftp服务器上的文本文件

python - 如何使用自定义概率分布进行随机选择

c# - DateTime 列上的 Mono InvalidOperationException (SQL Server)

java - java中的问号是什么意思?

python - 为什么这个 tensorflow 训练需要这么长时间?

Android Recyclerview vs ListView with Viewholder

java.util.date 到 String 使用 DateTimeFormatter

php - 在 Symfony2 (Doctrine) 和 MySQL 中启用微秒