File tree Expand file tree Collapse file tree 2 files changed +26
-2
lines changed
src/main/java/org/codefx/demo/effective_java/_06_unnecessary_objects Expand file tree Collapse file tree 2 files changed +26
-2
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments