Skip to content

Commit 7ebc620

Browse files
author
Nicolai Parlog
committed
[06] Create benchmark for String::replace and replaceAll
1 parent 4aa59ab commit 7ebc620

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package org.codefx.demo.effective_java._06_unnecessary_objects;
2+
3+
import org.openjdk.jmh.annotations.Benchmark;
4+
import org.openjdk.jmh.annotations.Param;
5+
6+
public class StringReplace extends ObjectCreationBenchmarks {
7+
8+
@Param({ "foobar", "foo:bar", "foo::bar" })
9+
private String string = "foobar";
10+
11+
@Benchmark
12+
public String replaceAll() {
13+
// NOTE unnecessary object:
14+
// `replaceAll` accepts a regex and hence has to compile it into a pattern
15+
return string.replaceAll(":", " ");
16+
}
17+
18+
@Benchmark
19+
public String replace() {
20+
// use `replace` instead if you don't need to replace a regex
21+
return string.replace(":", " ");
22+
}
23+
24+
}

src/main/java/org/codefx/demo/effective_java/_06_unnecessary_objects/StringSplit.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public class StringSplit extends ObjectCreationBenchmarks {
1414
public String[] singleColonSplit() {
1515
// NOTE unnecessary object:
1616
// For a single-character, `split` employs an optimization
17-
// and does not create a reg ex pattern
17+
// and does not create a regex pattern
1818
return string.split(":");
1919
}
2020

@@ -41,7 +41,7 @@ public String[] singleColonCode() {
4141
@Benchmark
4242
public String[] doubleColonSplit() {
4343
// NOTE unnecessary object:
44-
// Beyond a single character, `split` will create a create a reg ex pattern,
44+
// Beyond a single character, `split` will create a create a regex pattern,
4545
// which makes it rather slow
4646
return string.split("::");
4747
}

0 commit comments

Comments
 (0)