簡體   English   中英

為什么 Java 編譯的正則表達式的工作速度比在 String::split 中解釋的慢?

[英]Why Java compiled regex works slower then interpreted in String::split?

我正在嘗試改進以下代碼:

    public int applyAsInt(String ipAddress) {
        var ipAddressInArray = ipAddress.split("\\.");
        ...

所以我將正則表達式編譯成一個靜態常量:

    private static final Pattern PATTERN_DOT = Pattern.compile(".", Pattern.LITERAL);

    public int applyAsInt(String ipAddress) {
        var ipAddressInArray = PATTERN_DOT.split(ipAddress);
        ...

其余代碼保持不變。

令我驚訝的是,新代碼比以前的代碼慢。 以下是測試結果:

Benchmark                                (ipAddress)  Mode  Cnt    Score    Error  Units
ConverterBenchmark.mkyongConverter           1.2.3.4  avgt   10  166.456 ±  9.087  ns/op
ConverterBenchmark.mkyongConverter       120.1.34.78  avgt   10  168.548 ±  2.996  ns/op
ConverterBenchmark.mkyongConverter   129.205.201.114  avgt   10  180.754 ±  6.891  ns/op
ConverterBenchmark.mkyong2Converter          1.2.3.4  avgt   10  253.318 ±  4.977  ns/op
ConverterBenchmark.mkyong2Converter      120.1.34.78  avgt   10  263.045 ±  8.373  ns/op
ConverterBenchmark.mkyong2Converter  129.205.201.114  avgt   10  331.376 ± 53.092  ns/op

請幫助我理解為什么會這樣。

String.split有專門針對這個用例的代碼:

https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/lang/String.java#L3102

 /* fastpath if the regex is a * (1) one-char String and this character is not one of the * RegEx's meta characters ".$|()[{^?*+\\", or * (2) two-char String and the first char is the backslash and * the second is not the ascii digit or ascii letter. */

這意味着當使用split("\\.")時,字符串實際上不會使用正則表達式進行拆分 - 該方法直接在'.'處拆分字符串人物。

當您編寫PATTERN_DOT.split(ipAddress)時,無法進行此優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM