@@ -2226,7 +2226,10 @@ public Object optQuery(JSONPointer jsonPointer) {
22262226 */
22272227 @ SuppressWarnings ("resource" )
22282228 public static String quote (String string ) {
2229- Writer sw = new StringBuilderWriter ();
2229+ if (string == null || string .isEmpty ()) {
2230+ return "\" \" " ;
2231+ }
2232+ Writer sw = new StringBuilderWriter (string .length () + 2 );
22302233 try {
22312234 return quote (string , sw ).toString ();
22322235 } catch (IOException ignored ) {
@@ -2557,7 +2560,10 @@ public String toString() {
25572560 */
25582561 @ SuppressWarnings ("resource" )
25592562 public String toString (int indentFactor ) throws JSONException {
2560- Writer w = new StringBuilderWriter ();
2563+ // 6 characters are the minimum to serialise a key value pair e.g.: "k":1,
2564+ // and we don't want to oversize the initial capacity
2565+ int initialSize = map .size () * 6 ;
2566+ Writer w = new StringBuilderWriter (Math .max (initialSize , 16 ));
25612567 return this .write (w , indentFactor , 0 ).toString ();
25622568 }
25632569
@@ -2699,14 +2705,18 @@ static final Writer writeValue(Writer writer, Object value,
26992705 int indentFactor , int indent ) throws JSONException , IOException {
27002706 if (value == null || value .equals (null )) {
27012707 writer .write ("null" );
2708+ } else if (value instanceof String ) {
2709+ // assuming most values are Strings, so testing it earlier
2710+ quote (value .toString (), writer );
2711+ return writer ;
27022712 } else if (value instanceof JSONString ) {
27032713 Object o ;
27042714 try {
27052715 o = ((JSONString ) value ).toJSONString ();
27062716 } catch (Exception e ) {
27072717 throw new JSONException (e );
27082718 }
2709- writer .write (o != null ? o .toString () : quote ( value . toString ()) );
2719+ writer .write (o != null ? o .toString () : " \" \" " );
27102720 } else if (value instanceof Number ) {
27112721 // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary
27122722 final String numberAsString = numberToString ((Number ) value );
0 commit comments