Prefer writing chars instead of strings of length one (#1576)

This results in a noticeable performance improvement with most writer
implementations (including BufferedWriter).
This commit is contained in:
David Maplesden 2019-09-19 05:33:49 +12:00 committed by inder123
parent f885e602f1
commit 3958b1f78d

View File

@ -286,7 +286,7 @@ public class JsonWriter implements Closeable, Flushable {
*/
public JsonWriter beginArray() throws IOException {
writeDeferredName();
return open(EMPTY_ARRAY, "[");
return open(EMPTY_ARRAY, '[');
}
/**
@ -295,7 +295,7 @@ public class JsonWriter implements Closeable, Flushable {
* @return this writer.
*/
public JsonWriter endArray() throws IOException {
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]");
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, ']');
}
/**
@ -306,7 +306,7 @@ public class JsonWriter implements Closeable, Flushable {
*/
public JsonWriter beginObject() throws IOException {
writeDeferredName();
return open(EMPTY_OBJECT, "{");
return open(EMPTY_OBJECT, '{');
}
/**
@ -315,14 +315,14 @@ public class JsonWriter implements Closeable, Flushable {
* @return this writer.
*/
public JsonWriter endObject() throws IOException {
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}");
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, '}');
}
/**
* Enters a new scope by appending any necessary whitespace and the given
* bracket.
*/
private JsonWriter open(int empty, String openBracket) throws IOException {
private JsonWriter open(int empty, char openBracket) throws IOException {
beforeValue();
push(empty);
out.write(openBracket);
@ -333,7 +333,7 @@ public class JsonWriter implements Closeable, Flushable {
* Closes the current scope by appending any necessary whitespace and the
* given bracket.
*/
private JsonWriter close(int empty, int nonempty, String closeBracket)
private JsonWriter close(int empty, int nonempty, char closeBracket)
throws IOException {
int context = peek();
if (context != nonempty && context != empty) {
@ -562,7 +562,7 @@ public class JsonWriter implements Closeable, Flushable {
private void string(String value) throws IOException {
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
out.write("\"");
out.write('\"');
int last = 0;
int length = value.length();
for (int i = 0; i < length; i++) {
@ -589,7 +589,7 @@ public class JsonWriter implements Closeable, Flushable {
if (last < length) {
out.write(value, last, length - last);
}
out.write("\"");
out.write('\"');
}
private void newline() throws IOException {
@ -597,7 +597,7 @@ public class JsonWriter implements Closeable, Flushable {
return;
}
out.write("\n");
out.write('\n');
for (int i = 1, size = stackSize; i < size; i++) {
out.write(indent);
}