From 5243d57f9dece270ab58913c22b2211f1da4ee05 Mon Sep 17 00:00:00 2001 From: David Turner Date: Tue, 10 Oct 2017 12:08:22 -0400 Subject: [PATCH] Optimize newline processing This makes google-java-format as a whole run in about a third of the time on my (already-correctly-formatted) codebase. --- .../com/google/googlejavaformat/Newlines.java | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/Newlines.java b/core/src/main/java/com/google/googlejavaformat/Newlines.java index dbb82d3c5..86b017495 100644 --- a/core/src/main/java/com/google/googlejavaformat/Newlines.java +++ b/core/src/main/java/com/google/googlejavaformat/Newlines.java @@ -16,23 +16,27 @@ import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentHashMap; /** Platform-independent newline handling. */ public class Newlines { + private static Map> cache = new ConcurrentHashMap>(); + /** Returns the number of line breaks in the input. */ public static int count(String input) { - return Iterators.size(lineOffsetIterator(input)) - 1; + return lineOffsetList(input).size() - 1; } /** Returns the index of the first break in the input, or {@code -1}. */ public static int firstBreak(String input) { - Iterator it = lineOffsetIterator(input); - it.next(); - return it.hasNext() ? it.next() : -1; + List offsets = lineOffsetList(input); + return offsets.isEmpty() ? -1 : offsets.get(0); } private static final ImmutableSet BREAKS = ImmutableSet.of("\r\n", "\n", "\r"); @@ -94,7 +98,16 @@ public static boolean containsBreaks(String text) { /** Returns an iterator over the start offsets of lines in the input. */ public static Iterator lineOffsetIterator(String input) { - return new LineOffsetIterator(input); + return lineOffsetList(input).iterator(); + } + + private static List lineOffsetList(String input) { + List offsets = cache.get(input); + if (offsets == null) { + offsets = Lists.newArrayList(new LineOffsetIterator(input)); + cache.put(input, offsets); + } + return offsets; } /** Returns an iterator over lines in the input, including trailing whitespace. */