Skip to content

Commit aeca1a9

Browse files
committed
[JSC] Improve speed of JSON.stringify on arrays of similar objects
https://bugs.webkit.org/show_bug.cgi?id=329474 rdar://191337826 Reviewed by Yusuke Suzuki. This patch speeds up JSON.stringify in the case where we're stringifying an array of objects with repeated structures. It does this by maintaining a small cache keyed by structure IDs. This means that when we encounter a previously seen structure again, we don't have to reperform work like forEachProperty walks, enumerability and symbol checks, 8-bit name checks and escape scans. Tests: JSTests/stress/json-stringify-prepared-structure-large.js JSTests/stress/json-stringify-prepared-structure.js * Source/JavaScriptCore/runtime/JSONObject.cpp: (JSC::dynamicBufferLengths): (JSC::FastStringifier::preparedStructureSlot): (JSC::bufferMode>::FastStringifier): (JSC::bufferMode>::result): (JSC::bufferMode>::appendPreparedObjectKey): (JSC::bufferMode>::appendPreparedObject): (JSC::bufferMode>::appendUnpreparedObject): (JSC::bufferMode>::append): (JSC::recentResultsOverflowedStaticBuffer): (JSC::stringify): (JSC::bufferMode>::stringify): * Source/JavaScriptCore/runtime/VM.h: (JSC::VM::recentLatin1JSONStringifyLengths): (JSC::VM::recentUTF16JSONStringifyLengths): * JSTests/stress/json-stringify-prepared-structure-large.js: Added. (check): (armDynamicBufferFirst): (const.tails.string_appeared_here): (const.tails.string_appeared_here.toJSON): (makeBig.makeWide): (makeBig): (makeBig.makeNestedWide): (check.makeWide): * JSTests/stress/json-stringify-prepared-structure.js: Added. (check): (makeMasked): (makeTree): (makeChain): (makeWide): (new.Date): (toJSON): (check.const.withGetter.get b): Canonical link: https://commits.webkit.org/325490@main
1 parent 7fadf12 commit aeca1a9

4 files changed

Lines changed: 831 additions & 179 deletions

File tree

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Differential test for JSON.stringify's fast path on outputs larger than its static buffer (8192 characters), which
2+
// use the dynamic buffer, the Structure cache with its larger tables, and the hint of recent result lengths. The
3+
// reference output comes from the general Stringifier, which we force with an identity replacer.
4+
5+
const spaces = [undefined, 2];
6+
7+
function check(name, value) {
8+
for (const space of spaces) {
9+
const fast = JSON.stringify(value, null, space);
10+
const slow = JSON.stringify(value, (key, x) => x, space);
11+
if (fast !== slow) {
12+
let index = 0;
13+
while (index < fast.length && fast[index] === slow[index])
14+
++index;
15+
throw new Error(`${name}: mismatch with space ${JSON.stringify(space)} at ${index} (lengths ${fast.length} and ${slow.length})\n fast: ${fast.slice(Math.max(0, index - 40), index + 40)}\n slow: ${slow.slice(Math.max(0, index - 40), index + 40)}`);
16+
}
17+
}
18+
}
19+
20+
function makeBig(count, tail) {
21+
const rows = [];
22+
for (let i = 0; i < count; i++)
23+
rows.push({ id: i, name: 'item' + i, price: i + 0.25, tags: ['a', 'b'], flag: i % 2 === 0, extra: i % 7 === 0 ? undefined : { x: i } });
24+
if (tail !== undefined)
25+
rows.push(tail);
26+
return rows;
27+
}
28+
29+
const bigCount = 120;
30+
31+
// Two large results in a row make the next stringify try the dynamic buffer first.
32+
function armDynamicBufferFirst() {
33+
for (let i = 0; i < 2; i++) {
34+
if (JSON.stringify(makeBig(bigCount)).length <= 8192)
35+
throw new Error("Output should be larger than the static buffer");
36+
}
37+
}
38+
39+
check('big', makeBig(bigCount));
40+
check('big again', makeBig(bigCount));
41+
armDynamicBufferFirst();
42+
check('small after big', makeBig(5));
43+
check('small after small', makeBig(3));
44+
armDynamicBufferFirst();
45+
check('big after big', makeBig(bigCount));
46+
47+
// The fast path gives up after more than the static buffer's worth of output, which must still produce the right
48+
// result, and must not keep trying the dynamic buffer first for the calls after it.
49+
const tails = {
50+
'16-bit tail': { id: -1, name: '中文' },
51+
'Date tail': { id: -1, d: new Date(0) },
52+
'function tail': function () { },
53+
'toJSON tail': { toJSON() { return { id: -1 }; } },
54+
'symbol key tail': { [Symbol('s')]: 1, id: -1 },
55+
'escaped key tail': { 'k"ey': 1 },
56+
};
57+
58+
for (const name in tails) {
59+
armDynamicBufferFirst();
60+
check(`big with ${name}`, makeBig(bigCount, tails[name]));
61+
check(`small after big with ${name}`, makeBig(4));
62+
check(`big after big with ${name}`, makeBig(bigCount));
63+
}
64+
65+
armDynamicBufferFirst();
66+
check('big with 16-bit head', [{ id: -1, name: '中文' }, ...makeBig(bigCount)]);
67+
check('small after big with 16-bit head', makeBig(4));
68+
69+
// Nested wide objects fill the scratch space for recording Structures on the first visit.
70+
{
71+
function makeNestedWide(level, depth, seed) {
72+
const object = {};
73+
for (let i = 0; i < 31; i++)
74+
object[`l${level}_${i}`] = i % 2 ? seed + i : 'v' + seed + '_' + i;
75+
object[`l${level}_last`] = depth > 1 ? makeNestedWide(level + 1, depth - 1, seed + 1) : seed;
76+
return object;
77+
}
78+
const trees = [];
79+
for (let seed = 0; seed < 12; seed++)
80+
trees.push(makeNestedWide(0, 3, seed));
81+
check('big nested wide', trees);
82+
check('big nested wide 16-bit', [...trees, '中']);
83+
}
84+
85+
// Many properties in large output, so the dynamic buffer caches Structures the static buffer would not.
86+
{
87+
function makeWide(count, seed) {
88+
const object = {};
89+
for (let i = 0; i < count; i++)
90+
object['p' + i] = i % 3 === 0 ? seed + i : i % 3 === 1 ? 'str' + seed + '_' + i : (seed + i) / 4 + 0.5;
91+
return object;
92+
}
93+
const rows = [];
94+
for (let i = 0; i < 40; i++)
95+
rows.push(makeWide(20 + (i % 15), i));
96+
check('big wide', rows);
97+
check('big wide 16-bit', [...rows, '中']);
98+
}
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// Differential test for the Structure cache in JSON.stringify's fast path. The first object with a given Structure is
2+
// serialized the ordinary way, and later objects with the same Structure reuse its key text and read their values
3+
// straight from storage. Every case below serializes several objects of one shape. The reference output comes from
4+
// the general Stringifier, which we force with an identity replacer.
5+
6+
const spaces = [undefined, 2, '\t'];
7+
8+
function check(name, value) {
9+
for (const space of spaces) {
10+
const fast = JSON.stringify(value, null, space);
11+
const slow = JSON.stringify(value, (key, x) => x, space);
12+
if (fast !== slow) {
13+
let index = 0;
14+
while (index < fast.length && fast[index] === slow[index])
15+
++index;
16+
throw new Error(`${name}: mismatch with space ${JSON.stringify(space)} at ${index} (lengths ${fast.length} and ${slow.length})\n fast: ${fast.slice(Math.max(0, index - 40), index + 40)}\n slow: ${slow.slice(Math.max(0, index - 40), index + 40)}`);
17+
}
18+
}
19+
}
20+
21+
function shouldBe(actual, expected) {
22+
if (actual !== expected)
23+
throw new Error(`Expected ${expected} but got ${actual}`);
24+
}
25+
26+
shouldBe(JSON.stringify([{ a: undefined, b: 1 }, { a: undefined, b: 2 }]), '[{"b":1},{"b":2}]');
27+
shouldBe(JSON.stringify([{ a: 1, b: 2 }, { a: undefined, b: 3 }, { a: 4, b: undefined }, { a: undefined, b: undefined }]), '[{"a":1,"b":2},{"b":3},{"a":4},{}]');
28+
shouldBe(JSON.stringify([{ a: 1, b: 2 }, { a: 3, b: 4 }], null, 1), '[\n {\n "a": 1,\n "b": 2\n },\n {\n "a": 3,\n "b": 4\n }\n]');
29+
30+
// An undefined value in the first, a middle, the last, or every property, whether or not the first object of the
31+
// Structure has it.
32+
function makeMasked(keys, mask, seed) {
33+
const object = {};
34+
for (let i = 0; i < keys.length; i++)
35+
object[keys[i]] = (mask >> i) & 1 ? undefined : seed * 100 + i;
36+
return object;
37+
}
38+
39+
for (let firstMask = 0; firstMask < 8; firstMask++) {
40+
const keys = ['a', 'b', 'c'];
41+
const list = [makeMasked(keys, firstMask, 9)];
42+
for (let mask = 0; mask < 8; mask++) {
43+
list.push(makeMasked(keys, mask, mask));
44+
list.push(makeMasked(keys, mask, mask + 10));
45+
}
46+
check(`undefined mask ${firstMask}`, list);
47+
check(`undefined mask ${firstMask} nested`, { items: list, again: [list, { items: list }] });
48+
}
49+
50+
// Objects of the same Structure nested inside each other.
51+
function makeTree(depth, i) {
52+
if (!depth)
53+
return { value: i, children: [] };
54+
return { value: i, children: [makeTree(depth - 1, i + 1), makeTree(depth - 1, i + 2)] };
55+
}
56+
57+
function makeChain(length) {
58+
let object = { next: null, value: 0 };
59+
for (let i = 1; i < length; i++)
60+
object = { next: object, value: i };
61+
return object;
62+
}
63+
64+
check('tree', makeTree(5, 0));
65+
check('trees', [makeTree(3, 0), makeTree(2, 1), makeTree(0, 2)]);
66+
check('chains', [makeChain(1), makeChain(5), makeChain(20), { next: makeChain(3), value: 'x' }]);
67+
68+
// Key lengths below, at, and above the SIMD stride of both character widths (16 and 8).
69+
for (const length of [0, 1, 6, 7, 8, 9, 15, 16, 17, 31, 32, 33]) {
70+
const key = 'x'.repeat(length);
71+
const rows = [];
72+
for (let i = 0; i < 4; i++)
73+
rows.push({ [key]: i, y: i * 2, [key + 'z']: 'v' + i });
74+
check(`key length ${length}`, rows);
75+
check(`key length ${length} nested`, { rows, inner: { [key]: rows } });
76+
// A 16-bit string anywhere makes the output 16-bit.
77+
check(`key length ${length} 16-bit`, [...rows, '中']);
78+
check(`key length ${length} 16-bit first`, ['中', ...rows]);
79+
}
80+
81+
// Out-of-line properties, more properties than a Structure can cache, and various value types per property.
82+
function makeWide(count, seed) {
83+
const object = {};
84+
for (let i = 0; i < count; i++) {
85+
const kind = i % 4;
86+
object['p' + i] = kind === 0 ? seed + i : kind === 1 ? 'str' + seed + '_' + i : kind === 2 ? (seed + i) / 4 + 0.5 : i % 8 === 3;
87+
}
88+
return object;
89+
}
90+
91+
for (const count of [1, 4, 6, 7, 8, 16, 31, 32, 33, 40]) {
92+
const rows = [];
93+
for (let seed = 0; seed < 4; seed++)
94+
rows.push(makeWide(count, seed));
95+
check(`wide ${count}`, rows);
96+
check(`wide ${count} 16-bit`, [...rows, '中']);
97+
rows[2].added = 1;
98+
delete rows[3]['p' + (count >> 1)];
99+
check(`wide ${count} transitioned`, rows);
100+
}
101+
102+
// More distinct Structures than the cache holds: 8 for the static buffer, 128 for the dynamic buffer.
103+
for (const count of [1, 8, 9, 130]) {
104+
const list = [];
105+
for (let repeat = 0; repeat < 2; repeat++) {
106+
for (let s = 0; s < count; s++)
107+
list.push({ ['s' + s]: repeat, common: s, text: 'repeat ' + repeat + ' with some padding' });
108+
}
109+
check(`${count} structures`, list);
110+
check(`${count} structures 16-bit`, [...list, '中']);
111+
}
112+
113+
// Every kind of value in a property of a shared Structure.
114+
const rope = 'x'.repeat(40) + String(spaces.length);
115+
const values = [
116+
'plain', 'quo"te', 'back\\slash', 'new\nline', '\u0000control', 'tab\there', '\u007f', 'café', '中文', '😀', '\ud800',
117+
rope, rope + rope, '', 'a',
118+
0, -0, 1, -1, 2147483647, -2147483648, 2147483648, 0.5, -0.5, 1e21, 1e-7, 123456789012, NaN, Infinity, -Infinity,
119+
null, true, false, undefined, function () { }, Symbol('s'), new Date(0), { toJSON() { return 'toJSON'; } }, { toJSON() { return undefined; } },
120+
[], [1, 2, 3], [{ v: 1 }, { v: 2 }], [[], [[]]], {}, { nested: 1 }, { v: { v: { v: 1 } } }, new Number(3), new String('boxed'), new Boolean(false),
121+
];
122+
123+
for (let i = 0; i < values.length; i++) {
124+
check(`value ${i}`, [{ v: values[i] }, { v: values[i] }, { v: 1 }, { v: values[i] }]);
125+
check(`value ${i} after number`, [{ v: 1.5 }, { v: 2 }, { v: values[i] }, { v: 'str' }]);
126+
check(`value ${i} with siblings`, [{ a: 1, v: values[i], b: 'two' }, { a: 3, v: values[i], b: 'four' }, { a: 5, v: values[i], b: 6.5 }]);
127+
}
128+
129+
// All of the values interleaved through one Structure.
130+
{
131+
const rows = [];
132+
for (let round = 0; round < 2; round++) {
133+
for (let i = 0; i < values.length; i++)
134+
rows.push({ a: values[i], b: values[(i + round + 1) % values.length], c: i });
135+
}
136+
check('all values', rows);
137+
check('all values nested', { rows, rows2: [rows] });
138+
}
139+
140+
// Objects whose last property holds a wider object, so that serializing the first one fills the scratch space used to
141+
// record properties of the Structures being serialized. The innermost Structures aren't cached on the first visit and
142+
// are cached on a later one.
143+
function makeNestedWide(level, depth, seed) {
144+
const object = {};
145+
for (let i = 0; i < 31; i++)
146+
object[`l${level}_${i}`] = i % 2 ? seed + i : 'v' + seed + '_' + i;
147+
object[`l${level}_last`] = depth > 1 ? makeNestedWide(level + 1, depth - 1, seed + 1) : seed;
148+
return object;
149+
}
150+
151+
for (const depth of [2, 3, 5]) {
152+
const trees = [];
153+
for (let seed = 0; seed < 4; seed++)
154+
trees.push(makeNestedWide(0, depth, seed));
155+
check(`nested wide ${depth}`, trees);
156+
check(`nested wide ${depth} nested`, { trees, again: [trees] });
157+
check(`nested wide ${depth} 16-bit`, [...trees, '中']);
158+
}
159+
160+
// Properties that make a Structure ineligible, mixed in with ones that are eligible.
161+
{
162+
const hidden = { a: 1 };
163+
Object.defineProperty(hidden, 'hidden', { value: 2, enumerable: false });
164+
const withSymbol = { a: 1 };
165+
withSymbol[Symbol('s')] = 2;
166+
const withGetter = { a: 1, get b() { return 3; } };
167+
const withIndex = { 0: 'zero', a: 1 };
168+
const withEscapedKey = { 'k"ey': 1, 'new\nline': 2 };
169+
const withWideKey = { 'キー': 1, a: 2 };
170+
const hiddenToJSON = { a: 1 };
171+
Object.defineProperty(hiddenToJSON, 'toJSON', { value() { return 'hidden toJSON'; }, enumerable: false });
172+
const enumerableToJSON = { a: 1, toJSON: 5 };
173+
const nullPrototype = Object.create(null);
174+
nullPrototype.a = 1;
175+
const customPrototype = Object.create({ inherited: 1 });
176+
customPrototype.a = 1;
177+
const specials = [hidden, withSymbol, withGetter, withIndex, withEscapedKey, withWideKey, hiddenToJSON, enumerableToJSON, nullPrototype, customPrototype];
178+
const plain = () => ({ a: 1 });
179+
for (let i = 0; i < specials.length; i++) {
180+
check(`special ${i}`, [plain(), plain(), specials[i], plain(), specials[i], plain()]);
181+
check(`special ${i} first`, [specials[i], plain(), plain(), specials[i], plain()]);
182+
}
183+
check('specials', [plain(), ...specials, plain(), ...specials, plain()]);
184+
}

0 commit comments

Comments
 (0)