Repository navigation
Expand file tree
/
Copy pathSimdjsonTwitterBenchmark.cs
More file actions
622 lines (525 loc) · 33.8 KB
/
Copy pathSimdjsonTwitterBenchmark.cs
File metadata and controls
622 lines (525 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
using System.Buffers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using MessagePack;
using PolyType;
using PolyType.Abstractions;
using SimdjsonTwitter;
// The task of simdjson's own benchmark (github.com/simdjson/simdjson, benchmark/static_reflect/twitter_benchmark; the
// figures of its README: "twitter.json into native structs" and back), on this repo's serializer and on
// Nerdbank.MessagePack and System.Text.Json. simdjson does not handle the whole document: its three structs
// (twitter_data.h, "Simplified Twitter structures for benchmarking") hold 6 members of each status and 9 of its user,
// 1,602 of the document's 13,914 values, 81,927 B as JSON against the 466,906 B of the whole document minified.
//
// Serialize the structs, already in memory, to bytes: simdjson's benchmark_serialization_twitter. The structs here
// are the same three, member for member (uint64_t -> ulong, std::vector<Status> -> Status[]).
// Every row writes into ONE REUSED BUFFER through the library's IBufferWriter<byte> entry point (an
// ArrayBufferWriter reset before each call; System.Text.Json through a reused Utf8JsonWriter over it),
// as simdjson's bench_simdjson_reuse_buffer / bench_simdjson_to_reuse do. Unlike AnswerBenchmark and
// RedoxBenchmark, whose serialize rows return a new byte[] on purpose, this benchmark exists to stand
// next to simdjson's numbers (neuecc, 2026-12-03): the condition is the same for every row here and
// for simdjson, so no row is given an advantage.
// Deserialize the WHOLE document to the same structs: simdjson's benchmark_parsing_twitter scans all of
// twitter.json and fills those 15 members, skipping the rest. So the payload here is the whole document
// too - RE:Dox's complete Twitter graph (RedoxModels.cs) serialized by each library in each contract -
// and the target is a type that keeps only the 15: in the array contract a type that names the
// POSITIONS of those members in the complete graph ([Key(1)], [Key(2)], [Key(4)], [Key(12)], ...),
// in the map contract and in JSON the type that names them. A partial read of a larger document.
//
// STRINGS ARE UTF-8 ON BOTH SIDES. simdjson's std::string holds UTF-8 and is copied to and from the wire; a .NET string
// is UTF-16 and would be transcoded on every member, which is the larger part of this document (71% of the structs'
// JSON is string content, much of it Japanese). The members are therefore Utf8String, the sample type of the README's
// custom-formatter section: a ReadOnlyMemory<byte> written with WriteString(span) and read by copying the bytes out.
// The other two libraries get the same treatment through their own extension points, so that no row transcodes:
// a MessagePackConverter<Utf8String> for Nerdbank.MessagePack and a JsonConverter<Utf8String> for System.Text.Json.
//
// Setup is the correctness gate: every serialize row's output reads back to the same structs, and every deserialize
// row's result equals the structs System.Text.Json loads from the file (compared as JSON; all the types declare the
// same members in the same order).
//
// Usage:
// dotnet run -c Release -- --simdjson-check (setup gate only, in-process)
// dotnet run -c Release -- --filter "SimdjsonTwitterBenchmark.*" --iterations=10 --no-disasm
// Concurrent GC is off, as in RedoxBenchmark, whose data this reads.
//
// MEASURED round 1 (2026-12-03; i7-13700KF, .NET 11.0.0, ShortRun x 10 iterations, --no-disasm; us/op; THE SERIALIZE
// ROWS STILL RETURNED A NEW byte[] in this round, see round 2 for the reused buffer;
// columns V4 array | V4 map | Nerdbank array | Nerdbank map | System.Text.Json):
// serialize 4.96 | 6.15 | 11.98 | 17.53 | 167.4 writes 59,929 | 74,738 | 59,929 | 74,738 | 130,759 B
// deserialize 40.1 | 77.5 | 92.9 | 225.1 | 455.2 reads 221,308 | 407,428 | 221,308 | 407,428 | 631,515 B
// Every row allocates the same 58.55 KB (array) / 73.02 KB (map) on serialize and 88.96 KB on deserialize.
// simdjson itself ON THIS MACHINE, the same day (master 878a62b = 5.3.0, GCC 16.2.0 -O3 with static reflection, in the
// gcc:16 Docker image under WSL2; five runs, median): serialization 18.1 GB/s with a fresh allocation and 18.3 with a
// reused buffer, of its 81,927 B of JSON = 4.5 us; parsing 6.3 GB/s of the 631,515 B file = 100 us. (Its README has
// 11.2 and 5.11 GB/s, from a Xeon Gold 6548N and simdjson 5.0.2.) So with UTF-8 members V4 writes the structs in
// 4.96 us against simdjson's 4.5 (1.1x; 16.5 GB/s in simdjson's unit, 81,927 B of JSON over the time), and reads the
// 15 members out of the whole document in 40.1 us against simdjson's 100 (2.5x ahead; msgpack skips a value by its
// length, JSON has to scan it). With string members the serialize row read 17.6 us (measured before this file, on a
// RedoxBenchmark dataset since removed): UTF-16 to UTF-8 was 3.5x of the whole.
// WHERE THE 4.96 us OF ROUND 1 WENT (scratch Stopwatch probe, same day, best of 7 x 20,000 calls; us): the row 5.08; the same call into
// a reused ArrayBufferWriter 3.42 (map: 6.10 and 3.95); a new byte[59,929] plus one copy of the finished bytes 2.32, with
// GC.AllocateUninitializedArray 1.57, the copy alone 0.89; the 600 strings (56,318 B) copied one by one into a reused
// array 1.88. So a third of the row is handing the result over as a byte[] of its exact size (the bytes are written
// into a pooled buffer first, then an array is allocated and filled), and the encoding itself is 3.4 us against
// simdjson's 4.5 for its 81,927 B. simdjson's rows do not pay that step: its string_builder rows read the builder's
// buffer as a view, and its to_json rows write into the std::string they return (malloc does not zero, and a
// std::string may be longer than its content, so nothing is copied to size).
// System.Text.Json's serialize is dearer with Utf8String than with string (167 vs 127 us): its default encoder
// escapes non-ASCII as \uXXXX, which a UTF-8 source has to be decoded for; its row keeps the default options.
//
// MEASURED round 2 (2026-12-03, same machine and settings; THE SERIALIZE ROWS WRITE INTO THE REUSED BUFFER; us/op,
// columns V4 array | V4 map | Nerdbank array | Nerdbank map | System.Text.Json):
// serialize 3.21 | 5.47 | 8.84 | 13.23 | 87.5 no allocation (System.Text.Json: 312 B)
// deserialize 41.2 | 78.5 | 84.4 | 243.2 | 460.3 as round 1 (those rows did not change)
// simdjson's reuse rows on this machine: bench_simdjson_reuse_buffer 18.3 GB/s and bench_simdjson_to_reuse 18.5 GB/s
// of 81,927 B, i.e. 4.48 and 4.43 us. So V4 array is 1.4x ahead of simdjson (25.5 GB/s in simdjson's unit) and V4 map,
// the contract that writes the member names as JSON does, is 1.2x behind it (15.0 GB/s). Against round 1 the reused
// buffer took 1.75 us off the array row (4.96 -> 3.21) and 0.68 off the map row (6.15 -> 5.47).
//
// WHY THE MAP ROW IS BEHIND simdjson (scratch in-run A/B the same day, BenchmarkDotNet, same settings; not kept; us):
// generated map 5.30 (5.29 over a SpanWriteBuffer: the buffer type is not it) | generated array 3.17 (2.95 over the span)
// the generated map's own reservations, written by direct calls instead of formatters 3.57
// the same with each key written in the reservation of the string that follows it 3.06
// one reservation for the whole document, no capacity check, no formatter (the map / the array) 2.66 / 2.27
// So the format is not the limit: written by hand the map is 1.7x ahead of simdjson's 4.45. Of the 2.6 us between that
// and the generated formatters, 0.4 is capacity checks, 0.5 is the 600 keys that sit between two strings and get a
// reservation of their own, and 1.7 is the formatter machinery (formatter-to-formatter calls, depth tracking, null
// checks) - which costs only 0.7 in the array contract.
// THE BISECT (same day, scratch, not kept): the three generated map formatters copied verbatim into a factory in front of
// the default chain, then one thing taken out per variant; us, generated 5.30-5.40:
// the copy 4.91-5.11 (reproduces the generated formatters)
// no state.Enter() / state.Exit() 4.99-5.18 not it
// strings by buffer.WriteString(value.x.Span), no formatter field 5.36 not it
// Utf8StringFormatter in a field of its own type 4.87-4.96 not it
// the user formatter in a field of its own type (direct call) 5.10 not it: the dispatch is not the cost
// the user's members written inside the status formatter 3.62-3.98 <- 1.0 to 1.5 us
// status and user both written inside the root formatter's loop 3.19-3.23 <- 1.8 to 2.0 us, 1.4x AHEAD of simdjson
// So the map row loses to simdjson at the boundary between an object's formatter and the formatter of a nested object:
// the same code is 1.0-1.5 us dearer per 100 users as a method of its own than written in place. Not the interface
// call (a direct call to the concrete formatter changes nothing) and not the depth tracking. What it is at the machine
// level is NOT established: both the array and the map formatter of User enter with 8 pushes and a 280 / 328 B frame
// zeroed in the prolog, yet the array contract has at most 0.9 us to gain from the same flattening (generated 3.17
// against 2.27 by hand). NestedFormatterDispatchBenchmark round 11 found flattening neutral on small int-only types;
// it is not neutral here. Flattening nested [MessagePackObject] types in generated code would take away the
// resolver's say over the nested type (a factory placed in front could no longer substitute it): a design decision.
//
// HARDWARE COUNTERS on the bisect (same day, elevated; per op = 100 statuses; times run about 30% high under collection):
// instructions branches mispredicted
// generated map 130,516 23,980 44
// the copy 127,737 24,044 37
// no state.Enter / Exit 124,887 22,994 31
// strings written directly, no Enter / Exit 123,028 22,605 31
// the user formatter called as its own type 127,365 23,913 39
// the user written inside the status formatter 97,034 15,309 13
// status and user inside the root's loop 88,432 14,099 12
// generated ARRAY, for scale 92,242 16,112 16
// The user as a method of its own executes about 260 instructions and 73 branches more per user than the same code in
// place; the status as a method of its own, about 87 and 12, which is what a call, a prolog and an epilog are. So this
// is work, not latency or misprediction. It is the same whether the user is reached through the interface, through a
// field of the concrete type, or as a static or instance helper method of the status formatter (4.77-4.96 us, against
// 3.64 in place). NOT it: the depth countdown (MaxDepth 498 / 499 / 501 leave the counts where they are, so no
// StackGuard.Probe() is involved), tiering (every method reaches Tier 1), a loop (the Tier-1 code of the user
// formatter has none but five rounds of frame zeroing), the size of the code (466 instructions on its hot path against
// about 410 for the same part in place). WHERE those 260 instructions run is NOT found: they are not in the
// formatter's own Tier-1 listing. The next tool would be sampling by instruction pointer (ETW / VTune).
//
// FOUND (same day): CPU samples by instruction pointer (BenchmarkDotNet's --profiler ETW, elevated, 40 iterations, read
// with TraceEvent against the MethodLoadVerbose ranges). Share of the samples in the benchmark process:
// the copy: user formatter 31.1 | Memmove 27.3 | the BENCHMARK METHOD 13.1 | Utf8StringFormatter.Serialize 7.7
// | BufferWriterWriteBuffer.Advance 3.8 | UnsafeWriteRaw 3.4 | UnsafeWriteUInt64 3.3
// | WriteBufferExtensions.GetReference 2.8 | GetSpan 1.1 | UnsafeWriteStringHeader 0.8 | SerializeState.Exit 0.6
// user inside status: status formatter 65.1 | Memmove 27.4 | the benchmark method 1.5 | no helper on its own
// In the slow shape there is NO status formatter in the list: the JIT inlined its Serialize into the caller chain that
// ends in the benchmark method, where the inlining budget was already spent, so everything the status formatter calls
// ([AggressiveInlining] or not: GetReference, Advance, UnsafeWriteRaw, UnsafeWriteUInt64, the string formatter) stayed
// a real call - a quarter of the samples, and the 260 instructions per status the counters showed. With the user
// written inside it the status formatter is too large to be inlined, is compiled as a method of its own with a budget
// of its own, and every helper is inlined into it. So it was never about the user formatter.
// [MethodImpl(NoInlining)] on the copied Serialize methods gives the same without flattening anything:
// the copy 5.05 | NoInlining on all three Serialize 3.77 | NoInlining on the status formatter's alone 3.72 | user inside status 3.50
// That is the Serialize twin of what MapKeyEmitShapeBenchmark found on the read side, where ObjectEmitter has emitted
// [MethodImpl(NoInlining)] on every generated Deserialize since. 3.7 us is 1.2x AHEAD of simdjson's 4.45.
//
// MEASURED round 3 (2026-12-03, same machine and settings, AFTER ObjectEmitter.EmitSerialize got [MethodImpl(NoInlining)];
// us/op, columns V4 array | V4 map | Nerdbank array | Nerdbank map | System.Text.Json):
// serialize 2.92 | 3.71 | 11.9 | 13.4 | 89.0 (round 2: 3.21 | 5.47 | 8.84 | 13.23 | 87.5)
// deserialize 40.7 | 77.5 | 87.7 | 248.8 | 456.6
// V4 map is now 1.2x AHEAD of simdjson's 4.45 and V4 array 1.5x. (Nerdbank array's serialize reads 8.8 or 12 from one
// run to the next; nothing here touches it.) What the same generator change did elsewhere, same day: AnswerBenchmark
// serialize 435.8 -> 450.0 ns and AnswerMapBenchmark 507.4 -> 530.3 ns (+3% and +4.5%, with the rows it cannot touch
// moving -1% to +3% in the same runs); RedoxBenchmark serialize geomean +3.9% array / +2.0% map, with Nerdbank's rows
// +4.4% and V4's own deserialize +4.6% in the same run, so nothing measurable there. The Answer and RE:Dox baselines
// were taken hours earlier, before Docker Desktop was started on the machine.
// SETTLED by an interleaved A/B (Docker Desktop stopped; generator without, with, without, with the attribute; 15
// iterations; ns): AnswerBenchmark.SerializeV4 422.0 | 439.4 | 433.0 | 429.0 and AnswerMapBenchmark.SerializeV4
// 509.3 | 515.4 | 514.3 | 508.7 - the two states overlap (+1.6% and 0.0% on the means, with the rows the generator
// cannot touch moving 2-4% between the same runs). No cost on Answer that this can measure.
//
// MEASURED round 4 (2026-12-03, the generator as it is now, 15 iterations, Docker Desktop stopped; THE NUMBERS OF
// README.md AND OF THE CHARTS; us/op, columns V4 array | V4 map | Nerdbank array | Nerdbank map | System.Text.Json):
// serialize 2.95 | 3.73 | 8.57 | 13.39 | 85.3
// deserialize 38.3 | 75.7 | 82.4 | 229.0 | 446.0
// simdjson itself, NATIVELY on this machine for the same README (master 878a62b = 5.3.0; WinLibs GCC 16.2.0 -O3 with
// static reflection, CMake and Ninja from Visual Studio; five runs, median, GB/s): serialization 15.4 fresh
// string_builder | 18.9 reused string_builder | 17.5 to_json | 18.6 to_json into a reused string; parsing 5.8
// (ondemand) | 5.9 (simdjson::from). On Windows its fresh-allocation rows are behind its reuse rows, which they were
// not under glibc. The README compares against its reuse rows: 18.9 GB/s = 4.33 us and 5.9 GB/s = 107.7 us.
[GcConcurrent(false)]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class SimdjsonTwitterBenchmark
{
readonly Nerdbank.MessagePack.MessagePackSerializer nb = new();
readonly Nerdbank.MessagePack.MessagePackSerializer nbMap = new() { SerializeDefaultValues = Nerdbank.MessagePack.SerializeDefaultValuesPolicy.Always };
static readonly ITypeShape<TwitterData> dataShape = TypeShapeResolver.Resolve<TwitterData, SimdjsonWitness>();
static readonly ITypeShape<TwitterDataMap> dataMapShape = TypeShapeResolver.Resolve<TwitterDataMap, SimdjsonWitness>();
static readonly ITypeShape<TwitterDataAt> dataAtShape = TypeShapeResolver.Resolve<TwitterDataAt, SimdjsonWitness>();
// the one buffer every serialize row writes into, and System.Text.Json's writer over it
readonly ArrayBufferWriter<byte> output = new(512 * 1024);
readonly Utf8JsonWriter jsonWriter = new(new ArrayBufferWriter<byte>(16));
// the structs, loaded once
TwitterData data = default!;
TwitterDataMap dataMap = default!;
// what the serialize rows produce (kept for the gate and for the sizes)
byte[] v4Bytes = default!;
byte[] v4MapBytes = default!;
byte[] nbBytes = default!;
byte[] nbMapBytes = default!;
byte[] jsonBytes = default!;
// the whole document, as each deserialize row receives it
byte[] fileJson = default!;
byte[] wholeV4 = default!;
byte[] wholeV4Map = default!;
byte[] wholeNb = default!;
byte[] wholeNbMap = default!;
public int V4Length => v4Bytes.Length;
public int V4MapLength => v4MapBytes.Length;
public int NerdbankLength => nbBytes.Length;
public int NerdbankMapLength => nbMapBytes.Length;
public int JsonLength => jsonBytes.Length;
public int WholeFileLength => fileJson.Length;
public int WholeV4Length => wholeV4.Length;
public int WholeV4MapLength => wholeV4Map.Length;
[GlobalSetup]
public void Setup()
{
fileJson = File.ReadAllBytes(RedoxDataFiles.Locate("twitter.json"));
data = JsonSerializer.Deserialize<TwitterData>(fileJson) ?? throw new InvalidOperationException("twitter.json: System.Text.Json produced null");
dataMap = JsonSerializer.Deserialize<TwitterDataMap>(fileJson) ?? throw new InvalidOperationException("twitter.json: System.Text.Json produced null (map twin)");
var canon = JsonSerializer.SerializeToUtf8Bytes(data);
if (data.statuses is not { Length: 100 }) throw new InvalidOperationException($"verify failed: expected 100 statuses, got {data.statuses?.Length}");
Same(JsonSerializer.SerializeToUtf8Bytes(dataMap), "the map twin");
// serialize rows, and each output read back
v4Bytes = Written(SerializeV4Array());
v4MapBytes = Written(SerializeV4Map());
nbBytes = Written(SerializeNerdbankArray());
nbMapBytes = Written(SerializeNerdbankMap());
jsonBytes = Written(SerializeSystemTextJson());
if (!nbBytes.AsSpan().SequenceEqual(v4Bytes)) Console.WriteLine($"// note: Nerdbank array wire differs from V4's ({nbBytes.Length} B vs {v4Bytes.Length} B)");
if (!nbMapBytes.AsSpan().SequenceEqual(v4MapBytes)) Console.WriteLine($"// note: Nerdbank map wire differs from V4's ({nbMapBytes.Length} B vs {v4MapBytes.Length} B)");
Same(JsonSerializer.SerializeToUtf8Bytes(MessagePackSerializer.Deserialize<TwitterData>(v4Bytes)), "V4 array roundtrip");
Same(JsonSerializer.SerializeToUtf8Bytes(MessagePackSerializer.Deserialize<TwitterDataMap>(v4MapBytes)), "V4 map roundtrip");
Same(JsonSerializer.SerializeToUtf8Bytes(nb.Deserialize(nbBytes, dataShape)), "Nerdbank array roundtrip");
Same(JsonSerializer.SerializeToUtf8Bytes(nbMap.Deserialize(nbMapBytes, dataMapShape)), "Nerdbank map roundtrip");
Same(JsonSerializer.SerializeToUtf8Bytes(JsonSerializer.Deserialize<TwitterData>(jsonBytes)), "System.Text.Json roundtrip");
// the whole document in each library's own bytes
var whole = JsonSerializer.Deserialize<RedoxData.Twitter.Root>(fileJson)!;
var wholeMap = JsonSerializer.Deserialize<RedoxMapData.Twitter.Root>(fileJson)!;
wholeV4 = MessagePackSerializer.Serialize(whole);
wholeV4Map = MessagePackSerializer.Serialize(wholeMap);
wholeNb = nb.Serialize(whole, TypeShapeResolver.Resolve<RedoxData.Twitter.Root, RedoxData.RedoxWitness>());
wholeNbMap = nbMap.Serialize(wholeMap, TypeShapeResolver.Resolve<RedoxMapData.Twitter.Root, RedoxMapData.RedoxMapWitness>());
// deserialize rows: the 15 members out of the whole document
Same(JsonSerializer.SerializeToUtf8Bytes(DeserializeV4Array()), "V4 array, partial read");
Same(JsonSerializer.SerializeToUtf8Bytes(DeserializeV4Map()), "V4 map, partial read");
Same(JsonSerializer.SerializeToUtf8Bytes(DeserializeNerdbankArray()), "Nerdbank array, partial read");
Same(JsonSerializer.SerializeToUtf8Bytes(DeserializeNerdbankMap()), "Nerdbank map, partial read");
Same(JsonSerializer.SerializeToUtf8Bytes(DeserializeSystemTextJson()), "System.Text.Json, partial read");
byte[] Written(int count)
{
if (count != output.WrittenCount) throw new InvalidOperationException($"verify failed: the row returned {count} but the buffer holds {output.WrittenCount} B");
return output.WrittenSpan.ToArray();
}
void Same(byte[] json, string label)
{
if (!json.AsSpan().SequenceEqual(canon)) throw new InvalidOperationException($"verify failed: {label} differs from the structs loaded from twitter.json ({json.Length} B vs {canon.Length} B)");
}
}
[BenchmarkCategory("Serialize"), Benchmark(Baseline = true)]
public int SerializeV4Array()
{
output.ResetWrittenCount();
MessagePackSerializer.Serialize(output, data);
return output.WrittenCount;
}
[BenchmarkCategory("Serialize"), Benchmark]
public int SerializeV4Map()
{
output.ResetWrittenCount();
MessagePackSerializer.Serialize(output, dataMap);
return output.WrittenCount;
}
[BenchmarkCategory("Serialize"), Benchmark]
public int SerializeNerdbankArray()
{
output.ResetWrittenCount();
nb.Serialize(output, data, dataShape);
return output.WrittenCount;
}
[BenchmarkCategory("Serialize"), Benchmark]
public int SerializeNerdbankMap()
{
output.ResetWrittenCount();
nbMap.Serialize(output, dataMap, dataMapShape);
return output.WrittenCount;
}
[BenchmarkCategory("Serialize"), Benchmark]
public int SerializeSystemTextJson()
{
output.ResetWrittenCount();
jsonWriter.Reset(output);
JsonSerializer.Serialize(jsonWriter, data);
jsonWriter.Flush();
return output.WrittenCount;
}
[BenchmarkCategory("Deserialize"), Benchmark(Baseline = true)]
public TwitterDataAt DeserializeV4Array() => MessagePackSerializer.Deserialize<TwitterDataAt>(wholeV4)!;
[BenchmarkCategory("Deserialize"), Benchmark]
public TwitterDataMap DeserializeV4Map() => MessagePackSerializer.Deserialize<TwitterDataMap>(wholeV4Map)!;
[BenchmarkCategory("Deserialize"), Benchmark]
public TwitterDataAt DeserializeNerdbankArray() => nb.Deserialize(wholeNb, dataAtShape)!;
[BenchmarkCategory("Deserialize"), Benchmark]
public TwitterDataMap DeserializeNerdbankMap() => nbMap.Deserialize(wholeNbMap, dataMapShape)!;
// simdjson reads the file as it is, whitespace included
[BenchmarkCategory("Deserialize"), Benchmark]
public TwitterData DeserializeSystemTextJson() => JsonSerializer.Deserialize<TwitterData>(fileJson)!;
}
namespace SimdjsonTwitter
{
/// <summary>Nerdbank.MessagePack / PolyType shape witness for the simdjson structs.</summary>
[GenerateShapeFor<TwitterData>]
[GenerateShapeFor<TwitterDataMap>]
[GenerateShapeFor<TwitterDataAt>]
public partial class SimdjsonWitness;
// ------------------------------------------------------------------ Utf8String, and the same thing for each library
/// <summary>UTF-8 text kept as bytes: the sample type of the README's custom-formatter section.</summary>
[MessagePackFormatter(typeof(Utf8StringFormatter<,>))]
[Nerdbank.MessagePack.MessagePackConverter(typeof(Utf8StringNerdbankConverter))]
[JsonConverter(typeof(Utf8StringJsonConverter))]
public readonly struct Utf8String(ReadOnlyMemory<byte> utf8Bytes)
{
public Utf8String(string value) : this(Encoding.UTF8.GetBytes(value)) { }
[PropertyShape(Ignore = true)]
public ReadOnlyMemory<byte> Memory => utf8Bytes;
[PropertyShape(Ignore = true)]
public ReadOnlySpan<byte> Span => utf8Bytes.Span;
public override string ToString() => Encoding.UTF8.GetString(Span);
}
public sealed partial class Utf8StringFormatter<TWriteBuffer, TReadBuffer> : IMessagePackFormatter<TWriteBuffer, TReadBuffer, Utf8String>
{
public void Initialize(MessagePackFormatterResolver resolver)
{
}
public void Serialize(ref TWriteBuffer buffer, ref SerializeState state, Utf8String value)
{
buffer.WriteString(value.Span); // writes the bytes as they are; the caller guarantees valid UTF-8
}
public void Deserialize(ref TReadBuffer buffer, ref DeserializeState state, ref Utf8String value)
{
if (buffer.TryReadNil())
{
value = default;
return;
}
var byteCount = buffer.ReadStringHeader();
if (byteCount == 0)
{
value = default;
return;
}
// copy out: the read buffer may be pooled, so a span over it must not outlive the call
var bytes = GC.AllocateUninitializedArray<byte>(byteCount);
buffer.CopyTo(bytes);
buffer.Advance(byteCount);
value = new Utf8String(bytes);
}
}
/// <summary>Nerdbank.MessagePack: the same bytes in, the same bytes out.</summary>
public sealed class Utf8StringNerdbankConverter : Nerdbank.MessagePack.MessagePackConverter<Utf8String>
{
public override Utf8String Read(ref Nerdbank.MessagePack.MessagePackReader reader, Nerdbank.MessagePack.SerializationContext context)
{
if (reader.TryReadNil())
{
return default;
}
if (reader.TryReadStringSpan(out var span))
{
return span.IsEmpty ? default : new Utf8String(span.ToArray());
}
var sequence = reader.ReadStringSequence()!.Value;
return sequence.IsEmpty ? default : new Utf8String(sequence.ToArray());
}
public override void Write(ref Nerdbank.MessagePack.MessagePackWriter writer, in Utf8String value, Nerdbank.MessagePack.SerializationContext context)
{
writer.WriteString(value.Span);
}
}
/// <summary>System.Text.Json: the string token's UTF-8 bytes, unescaped when the token carries escapes.</summary>
public sealed class Utf8StringJsonConverter : JsonConverter<Utf8String>
{
public override bool HandleNull => true;
public override Utf8String Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return default;
}
var length = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length;
if (length == 0)
{
return default;
}
// the unescaped text is never longer than the token
var bytes = GC.AllocateUninitializedArray<byte>(length);
var written = reader.CopyString(bytes);
return new Utf8String(written == length ? bytes : bytes.AsMemory(0, written));
}
public override void Write(Utf8JsonWriter writer, Utf8String value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.Span);
}
}
#pragma warning disable IDE1006 // naming matches simdjson's structs and the JSON document
// ------------------------------------------------------------------ simdjson's three structs (twitter_data.h), array contract
/// <summary>struct TwitterData.</summary>
[MessagePackObject]
public sealed partial class TwitterData
{
[MessagePack.Key(0), Nerdbank.MessagePack.Key(0)]
public Status[]? statuses { get; set; }
}
/// <summary>struct Status.</summary>
[MessagePackObject]
public sealed partial class Status
{
[MessagePack.Key(0), Nerdbank.MessagePack.Key(0)]
public Utf8String created_at { get; set; }
[MessagePack.Key(1), Nerdbank.MessagePack.Key(1)]
public ulong id { get; set; }
[MessagePack.Key(2), Nerdbank.MessagePack.Key(2)]
public Utf8String text { get; set; }
[MessagePack.Key(3), Nerdbank.MessagePack.Key(3)]
public User? user { get; set; }
[MessagePack.Key(4), Nerdbank.MessagePack.Key(4)]
public ulong retweet_count { get; set; }
[MessagePack.Key(5), Nerdbank.MessagePack.Key(5)]
public ulong favorite_count { get; set; }
}
/// <summary>struct User.</summary>
[MessagePackObject]
public sealed partial class User
{
[MessagePack.Key(0), Nerdbank.MessagePack.Key(0)]
public ulong id { get; set; }
[MessagePack.Key(1), Nerdbank.MessagePack.Key(1)]
public Utf8String name { get; set; }
[MessagePack.Key(2), Nerdbank.MessagePack.Key(2)]
public Utf8String screen_name { get; set; }
[MessagePack.Key(3), Nerdbank.MessagePack.Key(3)]
public Utf8String location { get; set; }
[MessagePack.Key(4), Nerdbank.MessagePack.Key(4)]
public Utf8String description { get; set; }
[MessagePack.Key(5), Nerdbank.MessagePack.Key(5)]
public bool verified { get; set; }
[MessagePack.Key(6), Nerdbank.MessagePack.Key(6)]
public ulong followers_count { get; set; }
[MessagePack.Key(7), Nerdbank.MessagePack.Key(7)]
public ulong friends_count { get; set; }
[MessagePack.Key(8), Nerdbank.MessagePack.Key(8)]
public ulong statuses_count { get; set; }
}
// ------------------------------------------------------------------ the same structs, map contract (property-name keys)
// These also read the whole document in the map contract: a key the type does not declare is skipped.
[MessagePackObject(keyAsPropertyName: true)]
public sealed partial class TwitterDataMap
{
public StatusMap[]? statuses { get; set; }
}
[MessagePackObject(keyAsPropertyName: true)]
public sealed partial class StatusMap
{
public Utf8String created_at { get; set; }
public ulong id { get; set; }
public Utf8String text { get; set; }
public UserMap? user { get; set; }
public ulong retweet_count { get; set; }
public ulong favorite_count { get; set; }
}
[MessagePackObject(keyAsPropertyName: true)]
public sealed partial class UserMap
{
public ulong id { get; set; }
public Utf8String name { get; set; }
public Utf8String screen_name { get; set; }
public Utf8String location { get; set; }
public Utf8String description { get; set; }
public bool verified { get; set; }
public ulong followers_count { get; set; }
public ulong friends_count { get; set; }
public ulong statuses_count { get; set; }
}
// ------------------------------------------------------------------ the same 15 members AT THEIR POSITIONS in the whole document
// Deserialize only. The keys are those of RedoxData.Twitter.Root / Status / User (RedoxModels.cs): the array of a status
// has 25 or more elements and this type names six of them, so the formatter skips the others.
// MsgPack111 reports exactly that (an int-keyed type with many unused positions); here it is the point.
#pragma warning disable MsgPack111
[MessagePackObject]
public sealed partial class TwitterDataAt
{
[MessagePack.Key(0), Nerdbank.MessagePack.Key(0)]
public StatusAt[]? statuses { get; set; }
}
[MessagePackObject]
public sealed partial class StatusAt
{
[MessagePack.Key(1), Nerdbank.MessagePack.Key(1)]
public Utf8String created_at { get; set; }
[MessagePack.Key(2), Nerdbank.MessagePack.Key(2)]
public ulong id { get; set; }
[MessagePack.Key(4), Nerdbank.MessagePack.Key(4)]
public Utf8String text { get; set; }
[MessagePack.Key(12), Nerdbank.MessagePack.Key(12)]
public UserAt? user { get; set; }
[MessagePack.Key(17), Nerdbank.MessagePack.Key(17)]
public ulong retweet_count { get; set; }
[MessagePack.Key(18), Nerdbank.MessagePack.Key(18)]
public ulong favorite_count { get; set; }
}
[MessagePackObject]
public sealed partial class UserAt
{
[MessagePack.Key(0), Nerdbank.MessagePack.Key(0)]
public ulong id { get; set; }
[MessagePack.Key(2), Nerdbank.MessagePack.Key(2)]
public Utf8String name { get; set; }
[MessagePack.Key(3), Nerdbank.MessagePack.Key(3)]
public Utf8String screen_name { get; set; }
[MessagePack.Key(4), Nerdbank.MessagePack.Key(4)]
public Utf8String location { get; set; }
[MessagePack.Key(5), Nerdbank.MessagePack.Key(5)]
public Utf8String description { get; set; }
[MessagePack.Key(17), Nerdbank.MessagePack.Key(17)]
public bool verified { get; set; }
[MessagePack.Key(9), Nerdbank.MessagePack.Key(9)]
public ulong followers_count { get; set; }
[MessagePack.Key(10), Nerdbank.MessagePack.Key(10)]
public ulong friends_count { get; set; }
[MessagePack.Key(18), Nerdbank.MessagePack.Key(18)]
public ulong statuses_count { get; set; }
}
#pragma warning restore MsgPack111
}