为什么在Java 11中,对于空字符串,String.strip()比String.trim()快5倍

18

我遇到了一个有趣的场景。由于某种原因,在Java 11中,使用strip()处理只包含空格字符的空字符串时,速度比使用trim()快得多。

基准测试

public class Test {

    public static final String TEST_STRING = "   "; // 3 whitespaces

    @Benchmark
    @Warmup(iterations = 10, time = 200, timeUnit = MILLISECONDS)
    @Measurement(iterations = 20, time = 500, timeUnit = MILLISECONDS)
    @BenchmarkMode(Mode.Throughput)
    public void testTrim() {
        TEST_STRING.trim();
    }

    @Benchmark
    @Warmup(iterations = 10, time = 200, timeUnit = MILLISECONDS)
    @Measurement(iterations = 20, time = 500, timeUnit = MILLISECONDS)
    @BenchmarkMode(Mode.Throughput)
    public void testStrip() {
        TEST_STRING.strip();
    }

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
    }
}

结果

# Run complete. Total time: 00:04:16

Benchmark        Mode  Cnt           Score          Error  Units
Test.testStrip  thrpt  200  2067457963.295 ± 12353310.918  ops/s
Test.testTrim   thrpt  200   402307182.894 ±  4559641.554  ops/s

显然,strip() 的性能比 trim() 高出约5倍。

尽管对于非空字符串,结果几乎相同:

public class Test {

    public static final String TEST_STRING = " Test String ";

    @Benchmark
    @Warmup(iterations = 10, time = 200, timeUnit = MILLISECONDS)
    @Measurement(iterations = 20, time = 500, timeUnit = MILLISECONDS)
    @BenchmarkMode(Mode.Throughput)
    public void testTrim() {
        TEST_STRING.trim();
    }

    @Benchmark
    @Warmup(iterations = 10, time = 200, timeUnit = MILLISECONDS)
    @Measurement(iterations = 20, time = 500, timeUnit = MILLISECONDS)
    @BenchmarkMode(Mode.Throughput)
    public void testStrip() {
        TEST_STRING.strip();
    }

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
    }
}


# Run complete. Total time: 00:04:16

Benchmark        Mode  Cnt          Score         Error  Units
Test.testStrip  thrpt  200  126939018.461 ± 1462665.695  ops/s
Test.testTrim   thrpt  200  141868439.680 ± 1243136.707  ops/s
为什么?这是一个bug还是我的操作有误?

测试环境

  • CPU - Intel Xeon E3-1585L v5 @3.00 GHz
  • OS - Windows 7 SP 1 64-bit
  • JVM - Oracle JDK 11.0.1
  • Benchamrk - JMH v 1.19

更新

添加了更多不同字符串(空的,空格等)的性能测试。

基准测试

@Warmup(iterations = 5, time = 1, timeUnit = SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = SECONDS)
@Fork(value = 3)
@BenchmarkMode(Mode.Throughput)
public class Test {

    private static final String BLANK = "";              // Blank
    private static final String EMPTY = "   ";           // 3 spaces
    private static final String ASCII = "   abc    ";    // ASCII characters only
    private static final String UNICODE = "   абв    ";  // Russian Characters

    private static final String BIG = EMPTY.concat("Test".repeat(100)).concat(EMPTY);

    @Benchmark
    public void blankTrim() {
        BLANK.trim();
    }

    @Benchmark
    public void blankStrip() {
        BLANK.strip();
    }

    @Benchmark
    public void emptyTrim() {
        EMPTY.trim();
    }

    @Benchmark
    public void emptyStrip() {
        EMPTY.strip();
    }

    @Benchmark
    public void asciiTrim() {
        ASCII.trim();
    }

    @Benchmark
    public void asciiStrip() {
        ASCII.strip();
    }

    @Benchmark
    public void unicodeTrim() {
        UNICODE.trim();
    }

    @Benchmark
    public void unicodeStrip() {
        UNICODE.strip();
    }

    @Benchmark
    public void bigTrim() {
        BIG.trim();
    }

    @Benchmark
    public void bigStrip() {
        BIG.strip();
    }

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
    }
}

结果

# Run complete. Total time: 00:05:23

Benchmark           Mode  Cnt           Score          Error  Units
Test.asciiStrip    thrpt   15   356846913.133 ±  4096617.178  ops/s
Test.asciiTrim     thrpt   15   371319467.629 ±  4396583.099  ops/s
Test.bigStrip      thrpt   15    29058105.304 ±  1909323.104  ops/s
Test.bigTrim       thrpt   15    28529199.298 ±  1794655.012  ops/s
Test.blankStrip    thrpt   15  1556405453.206 ± 67230630.036  ops/s
Test.blankTrim     thrpt   15  1587932109.069 ± 19457780.528  ops/s
Test.emptyStrip    thrpt   15  2126290275.733 ± 23402906.719  ops/s
Test.emptyTrim     thrpt   15   406354680.805 ± 14359067.902  ops/s
Test.unicodeStrip  thrpt   15    37320438.099 ±   399421.799  ops/s
Test.unicodeTrim   thrpt   15    88226653.577 ±  1628179.578  ops/s

测试环境相同。

只有一个有趣的发现:包含Unicode字符的字符串使用trim()strip()更快。


2
strip() 是较新的方法...(不使用 getChar {unicode},仅检查尾部字符是否为空字符串,返回 "" {literal} 而非 new String(bytes)。) - user85421
3个回答

20

在 OpenJDK 11.0.1 中,String.strip()(实际上是 StringLatin1.strip())优化了将字符串修剪为一个空字符串的操作,通过返回一个已经进行内部化处理的 String 常量来实现:

public static String strip(byte[] value) {
    int left = indexOfNonWhitespace(value);
    if (left == value.length) {
        return "";
    }

虽然 String.trim()(实际上是 StringLatin1.trim())总是会分配一个新的 String 对象。在你的例子中,st = 3len = 3,因此

return ((st > 0) || (len < value.length)) ?
        newString(value, st, len - st) : null;

会在内部复制数组并创建一个新的String对象

return new String(Arrays.copyOfRange(val, index, index + len),
                      LATIN1);

假设我们可以更新基准以与非空的String进行比较,这不应受到上述 String.strip() 优化的影响:

@Warmup(iterations = 10, time = 200, timeUnit = MILLISECONDS)
@Measurement(iterations = 20, time = 500, timeUnit = MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
public class MyBenchmark {

  public static final String EMPTY_STRING = "   "; // 3 whitespaces
  public static final String NOT_EMPTY_STRING = "  a "; // 3 whitespaces with a in the middle

  @Benchmark
  public void testEmptyTrim() {
    EMPTY_STRING.trim();
  }

  @Benchmark
  public void testEmptyStrip() {
    EMPTY_STRING.strip();
  }

  @Benchmark
  public void testNotEmptyTrim() {
    NOT_EMPTY_STRING.trim();
  }

  @Benchmark
  public void testNotEmptyStrip() {
    NOT_EMPTY_STRING.strip();
  }

}

运行它显示strip()trim()在非空String上没有明显的区别。奇怪的是,将其修剪为空String仍然最慢:

Benchmark                       Mode  Cnt           Score           Error  Units
MyBenchmark.testEmptyStrip     thrpt  100  1887848947.416 ± 257906287.634  ops/s
MyBenchmark.testEmptyTrim      thrpt  100   206638996.217 ±  57952310.906  ops/s
MyBenchmark.testNotEmptyStrip  thrpt  100   399701777.916 ±   2429785.818  ops/s
MyBenchmark.testNotEmptyTrim   thrpt  100   385144724.856 ±   3928016.232  ops/s

1
谢谢解释!我有点想知道为什么JDK开发人员没有像strip()一样优化trim()。5倍的性能差异是一个巨大的差距。 - Mikhail Kholodkov

8

在查看OpenJDK的源代码后,假设Oracle版本的实现类似,我想差异可以解释为:

  • strip 将尝试查找第一个非空格字符,如果没有找到,则简单地返回 ""
  • trim 总是返回一个 new String(...the substring...)

可以说,在OpenJDK中,striptrim稍微优化了一点,因为它避免了创建新对象,除非必要。

(注意:我没有检查这些方法的Unicode版本。)


1

没错。在Java 11或更早版本中,似乎.trim()总是创建一个新的String(),而strip()则返回一个缓存的String。 您可以测试这个简单的代码并亲自证明。

public class JavaClass{
  public static void main(String[] args){
      //prints false
      System.out.println("     ".trim()=="");//CREATING A NEW STRING()
  }
}

vs

public class JavaClass{
  public static void main(String[] args){
      //prints true
      System.out.println("     ".strip()=="");//RETURNING CACHE ""
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接