|
| 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 | +import java.util.ArrayList; |
| 7 | + |
| 8 | +public class StringSplit extends ObjectCreationBenchmarks { |
| 9 | + |
| 10 | + @Param({ "foobar", "foo:bar", "foo::bar" }) |
| 11 | + private String string = "foobar"; |
| 12 | + |
| 13 | + @Benchmark |
| 14 | + public String[] singleColonSplit() { |
| 15 | + // NOTE unnecessary object: |
| 16 | + // For a single-character, `split` employs an optimization |
| 17 | + // and does not create a reg ex pattern |
| 18 | + return string.split(":"); |
| 19 | + } |
| 20 | + |
| 21 | + @Benchmark |
| 22 | + public String[] singleColonCode() { |
| 23 | + // this code is unlikely to be 100% correct (it is basically untested), |
| 24 | + // so I assume a proper implementation would potentially be a little slower, |
| 25 | + // but surely in the same order of magnitude |
| 26 | + ArrayList<String> matches = new ArrayList<>(); |
| 27 | + int lastIndex = 0; |
| 28 | + int nextIndex = string.indexOf(':'); |
| 29 | + while (nextIndex > -1) { |
| 30 | + if (nextIndex > lastIndex + 1) |
| 31 | + matches.add(string.substring(lastIndex, nextIndex)); |
| 32 | + lastIndex = nextIndex + 1; |
| 33 | + nextIndex = string.indexOf(':', nextIndex + 1); |
| 34 | + } |
| 35 | + if (string.length() > lastIndex) |
| 36 | + matches.add(string.substring(lastIndex)); |
| 37 | + |
| 38 | + return matches.toArray(String[]::new); |
| 39 | + } |
| 40 | + |
| 41 | + @Benchmark |
| 42 | + public String[] doubleColonSplit() { |
| 43 | + // NOTE unnecessary object: |
| 44 | + // Beyond a single character, `split` will create a create a reg ex pattern, |
| 45 | + // which makes it rather slow |
| 46 | + return string.split("::"); |
| 47 | + } |
| 48 | + |
| 49 | + @Benchmark |
| 50 | + public String[] doubleColonCode() { |
| 51 | + // this code is unlikely to be 100% correct (it is basically untested), |
| 52 | + // so I assume a proper implementation would potentially be a little slower, |
| 53 | + // but surely in the same order of magnitude |
| 54 | + ArrayList<String> matches = new ArrayList<>(); |
| 55 | + int lastIndex = 0; |
| 56 | + int nextIndex = string.indexOf("::"); |
| 57 | + while (nextIndex > -1) { |
| 58 | + if (nextIndex > lastIndex + 2) |
| 59 | + matches.add(string.substring(lastIndex, nextIndex)); |
| 60 | + lastIndex = nextIndex + 2; |
| 61 | + nextIndex = string.indexOf("::", nextIndex + 2); |
| 62 | + } |
| 63 | + if (string.length() > lastIndex) |
| 64 | + matches.add(string.substring(lastIndex)); |
| 65 | + |
| 66 | + return matches.toArray(String[]::new); |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | +} |
0 commit comments