Skip to content

Commit

Permalink
ISSUE-1773 CharacterReader: Reuse stringCache
Browse files Browse the repository at this point in the history
  • Loading branch information
chibenwa committed Jul 1, 2022
1 parent d85faf6 commit 32ebe91
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/main/java/org/jsoup/parser/CharacterReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
*/
public final class CharacterReader {
protected static final ThreadLocal<SoftReference<BufferRecycler>> _recyclerRef = new ThreadLocal<>();
protected static final ThreadLocal<SoftReference<String[]>> stringCacheRef = new ThreadLocal<>();

public static BufferRecycler getBufferRecycler() {
SoftReference<BufferRecycler> ref = _recyclerRef.get();
Expand All @@ -32,6 +33,18 @@ public static BufferRecycler getBufferRecycler() {
return br;
}

public static String[] getStringCache() {
SoftReference<String[]> ref = stringCacheRef.get();
String[] stringCache = (ref == null) ? null : ref.get();

if (stringCache == null) {
stringCache = new String[stringCacheSize];
ref = new SoftReference<>(stringCache);
stringCacheRef.set(ref);
}
return stringCache;
}

static final char EOF = (char) -1;
private static final int maxStringCacheLen = 12;
static final int maxBufferLen = 1024 * 32; // visible for testing
Expand All @@ -46,7 +59,7 @@ public static BufferRecycler getBufferRecycler() {
private int readerPos;
private int bufMark = -1;
private static final int stringCacheSize = 512;
private String[] stringCache = new String[stringCacheSize]; // holds reused strings in this doc, to lessen garbage
private String[] stringCache = getStringCache(); // holds reused strings in this doc, to lessen garbage

@Nullable private ArrayList<Integer> newlinePositions = null; // optionally track the pos() position of newlines - scans during bufferUp()
private int lineNumberOffset = 1; // line numbers start at 1; += newlinePosition[indexof(pos)]
Expand Down

0 comments on commit 32ebe91

Please sign in to comment.