diff options
author | Ron Shapiro <ronshapiro@google.com> | 2019-04-16 15:30:11 -0400 |
---|---|---|
committer | Ron Shapiro <ronshapiro@google.com> | 2019-04-16 15:30:11 -0400 |
commit | 02ece26b2e05f3b1306f67aacc3a8932a3e51d51 (patch) | |
tree | 3b4b454110655b9f91cdf7a5a19a19b9c7071f44 | |
parent | c4ac60e768c573cd1f682dac4d6922c05071c16c (diff) | |
download | javapoet-02ece26b2e05f3b1306f67aacc3a8932a3e51d51.tar.gz |
Memoize ClassName.simpleNames()
In addition to being used repeatedly in CodeWriter.lookupName(), the current implementation is N^2 (albeit for a usually low N) since it recursively calls itself on the enclosing class name. This should get rid of some of the garbage created in code writing.
-rw-r--r-- | src/main/java/com/squareup/javapoet/ClassName.java | 17 |
1 files changed, 13 insertions, 4 deletions
diff --git a/src/main/java/com/squareup/javapoet/ClassName.java b/src/main/java/com/squareup/javapoet/ClassName.java index e044985..b8dbd31 100644 --- a/src/main/java/com/squareup/javapoet/ClassName.java +++ b/src/main/java/com/squareup/javapoet/ClassName.java @@ -41,6 +41,8 @@ public final class ClassName extends TypeName implements Comparable<ClassName> { /** This class name, like "Entry" for java.util.Map.Entry. */ final String simpleName; + private List<String> simpleNames; + /** The full class name like "java.util.Map.Entry". */ final String canonicalName; @@ -108,11 +110,18 @@ public final class ClassName extends TypeName implements Comparable<ClassName> { } public List<String> simpleNames() { - List<String> simpleNames = new ArrayList<>(); - if (enclosingClassName != null) { - simpleNames.addAll(enclosingClassName().simpleNames()); + if (simpleNames != null) { + return simpleNames; + } + + if (enclosingClassName == null) { + simpleNames = Collections.singletonList(simpleName); + } else { + List<String> mutableNames = new ArrayList<>(); + mutableNames.addAll(enclosingClassName().simpleNames()); + mutableNames.add(simpleName); + simpleNames = Collections.unmodifiableList(mutableNames); } - simpleNames.add(simpleName); return simpleNames; } |