使用新的 java.time API 解析时区极其缓慢

2024-01-09

我刚刚将一个模块从旧的 java 日期迁移到新的 java.time API,并注意到性能大幅下降。它归结为用时区解析日期(我一次解析数百万个日期)。

解析不带时区的日期字符串(yyyy/MM/dd HH:mm:ss)速度很快 - 比旧的 java 日期快大约 2 倍,在我的 PC 上每秒大约 1.5M 操作。

但是,当模式包含时区时 (yyyy/MM/dd HH:mm:ss z),新版本性能下降约15倍java.timeAPI,而使用旧 API 时,它的速度与没有时区的情况一样快。请参阅下面的性能基准。

有谁知道我是否可以使用新的方法快速解析这些字符串java.timeAPI?目前,作为一种解决方法,我使用旧的 API 进行解析,然后将Date到 Instant,这不是特别好。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
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;

@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OperationsPerInvocation(1)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@State(Scope.Thread)
public class DateParsingBenchmark {

    private final int iterations = 100000;

    @Benchmark
    public void oldFormat_noZone(Blackhole bh, DateParsingBenchmark st) throws ParseException {

        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        for(int i=0; i<iterations; i++) {
            bh.consume(simpleDateFormat.parse("2000/12/12 12:12:12"));
        }
    }

    @Benchmark
    public void oldFormat_withZone(Blackhole bh, DateParsingBenchmark st) throws ParseException {

        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");

        for(int i=0; i<iterations; i++) {
            bh.consume(simpleDateFormat.parse("2000/12/12 12:12:12 CET"));
        }
    }

    @Benchmark
    public void newFormat_noZone(Blackhole bh, DateParsingBenchmark st) {

        DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                .appendPattern("yyyy/MM/dd HH:mm:ss").toFormatter();

        for(int i=0; i<iterations; i++) {
            bh.consume(dateTimeFormatter.parse("2000/12/12 12:12:12"));
        }
    }

    @Benchmark
    public void newFormat_withZone(Blackhole bh, DateParsingBenchmark st) {

        DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                .appendPattern("yyyy/MM/dd HH:mm:ss z").toFormatter();

        for(int i=0; i<iterations; i++) {
            bh.consume(dateTimeFormatter.parse("2000/12/12 12:12:12 CET"));
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(DateParsingBenchmark.class.getSimpleName()).build();
        new Runner(opt).run();    
    }
}

100K 次操作的结果:

Benchmark                                Mode  Cnt     Score     Error  Units
DateParsingBenchmark.newFormat_noZone    avgt    5    61.165 ±  11.173  ms/op
DateParsingBenchmark.newFormat_withZone  avgt    5  1662.370 ± 191.013  ms/op
DateParsingBenchmark.oldFormat_noZone    avgt    5    93.317 ±  29.307  ms/op
DateParsingBenchmark.oldFormat_withZone  avgt    5   107.247 ±  24.322  ms/op

UPDATE:

我刚刚对 java.time 类进行了一些分析,实际上,时区解析器的实现效率似乎相当低。仅仅解析一个独立的时区就是所有缓慢的原因。

@Benchmark
public void newFormat_zoneOnly(Blackhole bh, DateParsingBenchmark st) {

    DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
            .appendPattern("z").toFormatter();

    for(int i=0; i<iterations; i++) {
        bh.consume(dateTimeFormatter.parse("CET"));
    }
}

有一个类叫做ZoneTextPrinterParser in the java.time包,它在内部复制每个可用时区的集合parse()打电话(通过ZoneRulesProvider.getAvailableZoneIds()),这占了区域解析所花费时间的 99%。

好吧,答案可能是编写我自己的区域解析器,这也不太好,因为那样我就无法构建DateTimeFormatter via appendPattern().


As noted in your question and in my comment, ZoneRulesProvider.getAvailableZoneIds() creates a new set of all the available time zones' string representation (the keys of the static final ConcurrentMap<String, ZoneRulesProvider> ZONES) each time a time zone needs to be parsed.1

幸运的是,一个ZoneRulesProvider is an abstract被设计为子类的类。方法protected abstract Set<String> provideZoneIds()负责填充ZONES。因此,如果子类提前知道时间,则可以仅提供所需的时区all要使用的时区。由于该类将提供比包含数百个条目的默认提供程序更少的条目,因此它有可能显着减少getAvailableZoneIds().

The ZoneRulesProvider API https://docs.oracle.com/javase/8/docs/api/java/time/zone/ZoneRulesProvider.html提供有关如何注册的说明。请注意,提供程序无法取消注册,只能进行补充,因此删除默认提供程序并添加您自己的提供程序并不是简单的事情。系统属性java.time.zone.DefaultZoneRulesProvider定义默认提供者。如果返回的话null (via System.getProperty("...")然后加载 JVM 臭名昭著的提供程序。使用System.setProperty("...", "fully-qualified name of a concrete ZoneRulesProvider class")人们可以提供自己的提供商,这就是第二段中讨论的提供商。

总而言之,我建议:

  1. 子类化abstract class ZoneRulesProvider
  2. 实现了protected abstract Set<String> provideZoneIds()仅包含所需的时区。
  3. 将系统属性设置为此类。

I did not do it myself, but I am sure it will fail for some reason think it will work.


1 It is suggested in the comments of the question that the exact nature of the invocation might have changed between 1.8 versions.

Edit:找到更多信息

上述默认ZoneRulesProvider is final class TzdbZoneRulesProvider位于java.time.zone。该类中的区域是从路径读取的:JAVA_HOME/lib/tzdb.dat(就我而言,它位于 JDK 的 JRE 中)。该文件确实包含许多区域,这里是一个片段:

 TZDB  2014cJ Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers 
Africa/Asmara 
Africa/Asmera 
Africa/Bamako 
Africa/Bangui 
Africa/Banjul 
Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti 
Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone 
Africa/Harare Africa/Johannesburg Africa/Juba Africa/Kampala Africa/Khartoum 
Africa/Kigali Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome 
Africa/Luanda Africa/Lubumbashi 
Africa/Lusaka 
Africa/Malabo 
Africa/Maputo 
Africa/Maseru Africa/Mbabane Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena 
Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina America/Argentina/Buenos_Aires America/Argentina/Catamarca  America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia 
America/Aruba America/Asuncion America/Atikokan America/Atka 
America/Bahia

Then If one finds a way to create a similar file with only the needed zones and load that one instead, the performance issues will probably not surely be resolved.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用新的 java.time API 解析时区极其缓慢 的相关文章

随机推荐