Fix O(N^2) string concatenation in JSON encoder

This commit is contained in:
Vladimir Grichina 2019-01-23 15:39:41 -08:00
parent 5855cde762
commit e564e7171c

View File

@ -3,13 +3,13 @@ declare function logF64(val: f64): void;
export class JSONEncoder { export class JSONEncoder {
private isFirstKey: boolean = true private isFirstKey: boolean = true
private inObject: Array<boolean> = [false] private result: string[] = new Array<string>();
private result: string = ""
serialize(): Uint8Array { serialize(): Uint8Array {
// TODO: Write directly to UTF8 bytes // TODO: Write directly to UTF8 bytes
let utf8ptr = this.result.toUTF8(); let result = this.toString();
let buffer = new Uint8Array(this.result.lengthUTF8); let utf8ptr = result.toUTF8();
let buffer = new Uint8Array(result.lengthUTF8);
for (let i = 0; i < buffer.length; i++) { for (let i = 0; i < buffer.length; i++) {
buffer[i] = load<u8>(utf8ptr + i); buffer[i] = load<u8>(utf8ptr + i);
} }
@ -17,7 +17,7 @@ export class JSONEncoder {
} }
toString(): String { toString(): String {
return this.result; return this.result.join("");
} }
setString(name: string, value: string): void { setString(name: string, value: string): void {
@ -44,7 +44,6 @@ export class JSONEncoder {
this.writeKey(name); this.writeKey(name);
this.write("["); this.write("[");
this.isFirstKey = true this.isFirstKey = true
this.inObject.push(false);
return true; return true;
} }
@ -56,7 +55,6 @@ export class JSONEncoder {
this.writeKey(name); this.writeKey(name);
this.write("{"); this.write("{");
this.isFirstKey = true this.isFirstKey = true
this.inObject.push(true);
return true; return true;
} }
@ -116,6 +114,6 @@ export class JSONEncoder {
} }
private write(str: string): void { private write(str: string): void {
this.result += str; this.result.push(str);
} }
} }