From 410b4a8c62de693d38a0ee9a566a4a4c0863f934 Mon Sep 17 00:00:00 2001 From: Mohammad Yasir Date: Thu, 16 Feb 2017 02:51:02 +0530 Subject: [PATCH] Optimizing for memory --- .../com/google/gson/stream/JsonReader.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/gson/src/main/java/com/google/gson/stream/JsonReader.java b/gson/src/main/java/com/google/gson/stream/JsonReader.java index 9c55c436..995be32c 100644 --- a/gson/src/main/java/com/google/gson/stream/JsonReader.java +++ b/gson/src/main/java/com/google/gson/stream/JsonReader.java @@ -985,7 +985,7 @@ public class JsonReader implements Closeable { private String nextQuotedValue(char quote) throws IOException { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. char[] buffer = this.buffer; - StringBuilder builder = new StringBuilder(); + StringBuilder builder = null; while (true) { int p = pos; int l = limit; @@ -996,12 +996,23 @@ public class JsonReader implements Closeable { if (c == quote) { pos = p; - builder.append(buffer, start, p - start - 1); - return builder.toString(); + int len = p - start - 1; + if(null == builder) { + return new String(buffer, start, len); + } else { + builder.append(buffer, start, len); + return builder.toString(); + } } else if (c == '\\') { pos = p; - builder.append(buffer, start, p - start - 1); - builder.append(readEscapeCharacter()); + int len = p - start - 1; + char escapeChar = readEscapeCharacter(); + if(null == builder) { + int estimatedLength = (len + pos - p) * 2; + builder = new StringBuilder(estimatedLength < 16 ? 16 : estimatedLength); + } + builder.append(buffer, start, len); + builder.append(escapeChar); p = pos; l = limit; start = p; @@ -1011,6 +1022,11 @@ public class JsonReader implements Closeable { } } + if(null == builder) { + int len = (p - start) * 2; + initialLength = len; + builder = new StringBuilder(len < 16 ? 16 : len); + } builder.append(buffer, start, p - start); pos = p; if (!fillBuffer(1)) {