|
6 | 6 |
|
7 | 7 | import java.io.Closeable; |
8 | 8 | import java.io.IOException; |
9 | | -import java.io.StringWriter; |
10 | 9 | import java.io.Writer; |
11 | 10 | import java.lang.annotation.Annotation; |
12 | 11 | import java.lang.reflect.Field; |
@@ -2266,7 +2265,10 @@ public Object optQuery(JSONPointer jsonPointer) { |
2266 | 2265 | */ |
2267 | 2266 | @SuppressWarnings("resource") |
2268 | 2267 | public static String quote(String string) { |
2269 | | - StringWriter sw = new StringWriter(); |
| 2268 | + if (string == null || string.isEmpty()) { |
| 2269 | + return "\"\""; |
| 2270 | + } |
| 2271 | + Writer sw = new StringBuilderWriter(string.length() + 2); |
2270 | 2272 | try { |
2271 | 2273 | return quote(string, sw).toString(); |
2272 | 2274 | } catch (IOException ignored) { |
@@ -2665,7 +2667,10 @@ public String toString() { |
2665 | 2667 | */ |
2666 | 2668 | @SuppressWarnings("resource") |
2667 | 2669 | public String toString(int indentFactor) throws JSONException { |
2668 | | - StringWriter w = new StringWriter(); |
| 2670 | + // 6 characters are the minimum to serialise a key value pair e.g.: "k":1, |
| 2671 | + // and we don't want to oversize the initial capacity |
| 2672 | + int initialSize = map.size() * 6; |
| 2673 | + Writer w = new StringBuilderWriter(Math.max(initialSize, 16)); |
2669 | 2674 | return this.write(w, indentFactor, 0).toString(); |
2670 | 2675 | } |
2671 | 2676 |
|
@@ -2808,13 +2813,18 @@ static final Writer writeValue(Writer writer, Object value, |
2808 | 2813 | if (value == null || value.equals(null)) { |
2809 | 2814 | writer.write("null"); |
2810 | 2815 | } else if (value instanceof JSONString) { |
| 2816 | + // JSONString must be checked first, so it can overwrite behaviour of other types below |
2811 | 2817 | Object o; |
2812 | 2818 | try { |
2813 | 2819 | o = ((JSONString) value).toJSONString(); |
2814 | 2820 | } catch (Exception e) { |
2815 | 2821 | throw new JSONException(e); |
2816 | 2822 | } |
2817 | 2823 | writer.write(o != null ? o.toString() : quote(value.toString())); |
| 2824 | + } else if (value instanceof String) { |
| 2825 | + // assuming most values are Strings, so testing it early |
| 2826 | + quote(value.toString(), writer); |
| 2827 | + return writer; |
2818 | 2828 | } else if (value instanceof Number) { |
2819 | 2829 | // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary |
2820 | 2830 | final String numberAsString = numberToString((Number) value); |
|
0 commit comments