[英]Why is String.strip() 5 times faster than String.trim() for blank string In Java 11
我遇到了一個有趣的場景。 出於某種原因,對於空白字符串(僅包含空格)的strip()
明顯快於Java 11中的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
怎么會? 這是一個錯誤還是我做錯了?
測試環境
為不同的字符串添加了更多性能測試(空,空白等)。
基准
@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()
更快
在OpenJDK 11.0.1上, String.strip()
(實際上是StringLatin1.strip()
)通過返回一個StringLatin1.strip()
化的String
常量來優化剝離到空String
:
public static String strip(byte[] value) {
int left = indexOfNonWhitespace(value);
if (left == value.length) {
return "";
}
而String.trim()
(實際上是StringLatin1.trim()
)總是分配一個新的String
對象。 在你的例子中st = 3
和len = 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
不應受提及的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();
}
}
運行它顯示非空String
strip()
和trim()
之間沒有顯着差異。 奇怪的是,修剪到空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
在查看OpenJDK的源代碼之后,假設Oracle版本的實現類似,我想可以通過以下事實來解釋差異。
strip
將嘗試查找第一個非空白字符,如果找不到,則只返回""
trim
將始終返回一個new String(...the substring...)
有人可能會說, strip
只比trim
更優化,至少在OpenJDK中,因為除非必要,否則它會躲避新對象的創建。
(注意:我沒有麻煩地檢查這些方法的unicode版本。)
是的。 在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 ""
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.