From ff7aa3f3314e9e9ac50f3b8b259126ad379aead6 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Sat, 28 Aug 2010 07:29:22 +0000 Subject: [PATCH] Escape only the required characters when emitting JSON. This means that instead of emitting ["foo\nbar", "baz"] we'll emit this: ["foo bar", baz"] This simple change measured about ~35% faster for in-memory writes! --- .../com/google/gson/stream/JsonWriter.java | 39 +++---------------- 1 file changed, 5 insertions(+), 34 deletions(-) diff --git a/gson/src/main/java/com/google/gson/stream/JsonWriter.java b/gson/src/main/java/com/google/gson/stream/JsonWriter.java index e60b75d5..991edab4 100644 --- a/gson/src/main/java/com/google/gson/stream/JsonWriter.java +++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java @@ -384,43 +384,14 @@ public final class JsonWriter implements Closeable { * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." */ - switch (c) { - case '"': - case '\\': - case '/': + if (c == '"' || c == '\\') { out.write('\\'); out.write(c); - break; - - case '\t': - out.write("\\t"); - break; - - case '\b': - out.write("\\b"); - break; - - case '\n': - out.write("\\n"); - break; - - case '\r': - out.write("\\r"); - break; - - case '\f': - out.write("\\f"); - break; - - default: - if (c <= 0x1F) { - out.write(String.format("\\u%04x", (int) c)); - } else { - out.write(c); - } - break; + } else if (c <= 0x1F) { + out.write(String.format("\\u%04x", (int) c)); + } else { + out.write(c); } - } out.write("\""); }