Repository navigation
Expand file tree
/
Copy pathbench.php
More file actions
1427 lines (1331 loc) · 54.1 KB
/
Copy pathbench.php
File metadata and controls
1427 lines (1331 loc) · 54.1 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// bench.php: phpser vs igbinary, native serialize(), and msgpack on the
// shapes that actually show up in cache. igbinary is the reference column
// when available, otherwise phpser; deltas are reported against that column.
//
// Text (default):
// php -d extension=./modules/phpser.so -d extension=igbinary.so bench.php
//
// HTML page (writes a self-contained doc to stdout):
// php ... bench.php --html > docs/index.html
//
// Knobs (env): BENCH_ITERS (inner loop, default 1000, minimum 1),
// BENCH_REPS (timed repetitions, median+IQR reported, default 35),
// BENCH_WARMUP (untimed warmup iters per op, default 100, 0 disables).
//
// --extended appends groups after the default table (--only-extended skips
// the default table; both work with text, --html, and
// --format=json; the default table itself is unchanged):
// shapes single values, ['data' => ..., 'ttl' => 60] envelopes, rowsets
// whose tags arrays are heap-distinct or one shared heap array
// app Laravel-app shapes (Eloquent model/collection, Carbon, wallet,
// queue job, catalog, JWKS); reference is native serialize()
// signed phpser_*_signed vs igbinary/serialize framed with hash_hmac()
// gc_retained decode N copies kept alive with the collector ON vs OFF;
// reports automatic gc runs (needs pcntl for per-sample forks)
// Extended knobs: BENCH_EXT_REPS (default min(BENCH_REPS, 15)),
// BENCH_EXT_SAMPLE_MS (per-sample budget used to size inner loops, default
// 40, capped at BENCH_ITERS), BENCH_GC_REPS (default 5), BENCH_GC_KEEP
// (default 200), BENCH_GC_MEM_MB (retained-set budget, default 256).
//
// Opcache: production runs with opcache, which stores script literals as
// shared-memory interned strings and immutable arrays. To measure that
// configuration:
// php -d zend_extension=opcache -d opcache.enable_cli=1 \
// -d extension=./modules/phpser.so -d extension=igbinary.so bench.php --extended
// (drop the zend_extension flag when opcache is already loaded by php.ini).
declare(strict_types=1);
function mk_rowset(int $rows): array {
$out = [];
for ($i = 0; $i < $rows; $i++) {
$out[] = [
'id' => $i,
'user_id' => 1000 + ($i % 50),
'name' => 'row_' . $i,
'created_at' => '2026-05-19T12:00:00Z',
'amount' => $i * 1.07,
'active' => ($i % 3) === 0,
'tags' => ['a', 'b', 'c'],
];
}
return $out;
}
function distinct_string(string $value): string {
return substr($value . "\0", 0, strlen($value));
}
function mk_rowset_distinct(int $rows): array {
$out = mk_rowset($rows);
$rowCount = count($out);
for ($i = 0; $i < $rowCount; $i++) {
$out[$i]['created_at'] = distinct_string($out[$i]['created_at']);
$tagCount = count($out[$i]['tags']);
for ($j = 0; $j < $tagCount; $j++) {
$out[$i]['tags'][$j] = distinct_string($out[$i]['tags'][$j]);
}
}
return $out;
}
function mk_numeric_packed(int $n): array {
return range(0, $n - 1);
}
// Unsorted ints at realistic magnitudes. range() shapes collapse to a
// constant-size affine run, so this is the shape that keeps the linear
// per-element integer path measured. Fixed seed keeps payload bytes stable.
function mk_numeric_rand(int $n): array {
mt_srand(42);
$out = [];
for ($i = 0; $i < $n; $i++) $out[] = mt_rand(0, 1000000);
return $out;
}
function mk_deep_nested(int $depth): array {
$cur = ['leaf' => 42];
for ($i = 0; $i < $depth; $i++) {
$cur = ['next' => $cur, 'i' => $i];
}
return $cur;
}
// DTO batches measure class lookup and property handling absent from array rowsets.
final class UserDto {
public function __construct(
public int $id,
public int $tenant_id,
public string $name,
public string $email,
public ?string $phone,
public string $created_at,
public bool $is_active,
public array $tags,
) {}
}
final class OrderDto {
public function __construct(
public int $id,
public int $user_id,
public string $sku,
public float $amount,
public string $currency,
public string $status,
public ?string $shipped_at,
) {}
}
function mk_dto_users(int $n): array {
$out = [];
for ($i = 0; $i < $n; $i++) {
$out[] = new UserDto(
id: $i,
tenant_id: 1000 + ($i % 50),
name: 'user_' . $i,
email: "user{$i}@example.com",
phone: ($i % 3 === 0) ? null : '+1-555-' . str_pad((string)$i, 4, '0', STR_PAD_LEFT),
created_at: '2026-05-19T12:00:00Z',
is_active: ($i % 7) !== 0,
tags: ['active', 'verified', 'beta'],
);
}
return $out;
}
// Interleave two classes to exercise mixed-class lookup.
function mk_dto_mixed(int $users): array {
$out = [];
for ($i = 0; $i < $users; $i++) {
$orders = [];
for ($j = 0; $j < 3; $j++) {
$orders[] = new OrderDto(
id: $i * 10 + $j,
user_id: $i,
sku: 'SKU-' . ($i * 10 + $j),
amount: ($i + $j) * 12.99,
currency: 'USD',
status: ['pending', 'shipped', 'delivered'][$j % 3],
shipped_at: $j === 0 ? null : '2026-05-19T12:00:00Z',
);
}
$out[] = [
'user' => new UserDto(
id: $i,
tenant_id: 1000 + ($i % 50),
name: 'user_' . $i,
email: "user{$i}@example.com",
phone: null,
created_at: '2026-05-19T12:00:00Z',
is_active: true,
tags: ['active'],
),
'orders' => $orders,
];
}
return $out;
}
// --extended fixtures. Everything below feeds only the --extended groups; the
// default table above never touches it.
// Rebuilds a list element by element so the result is a refcounted heap array
// rather than the immutable literal (array_values() would return the input).
function distinct_list(array $src): array {
$out = [];
foreach ($src as $v) $out[] = $v;
return $out;
}
function mk_rowset_tags_distinct(int $rows): array {
$out = mk_rowset($rows);
foreach ($out as $i => $row) $out[$i]['tags'] = distinct_list($row['tags']);
return $out;
}
function mk_rowset_tags_shared(int $rows): array {
$out = mk_rowset($rows);
$shared = distinct_list(['a', 'b', 'c']);
foreach ($out as $i => $row) $out[$i]['tags'] = $shared;
return $out;
}
function mk_small_assoc(): array {
return [
'id' => 42, 'name' => distinct_string('alice'), 'email' => distinct_string('alice@example.com'),
'active' => true, 'score' => 1.5, 'roles' => distinct_list(['admin', 'editor']),
];
}
function fx_hex(string $seed, int $len): string {
return substr(hash('sha256', $seed), 0, $len);
}
function fx_uuid7(string $seed): string {
$h = hash('sha256', $seed);
return sprintf('%s-%s-7%s-%s-%s',
substr($h, 0, 8), substr($h, 8, 4), substr($h, 13, 3), substr($h, 16, 4), substr($h, 20, 12));
}
function fx_ts(int $offset): string {
return gmdate('Y-m-d H:i:s', 1767225600 + $offset);
}
// Mirrors the property surface of an Illuminate model instance as it sits in
// cache: framework defaults (mostly empty arrays / null / false), class-level
// casts/fillable/guarded literals, and attributes === original after a fetch.
class EloquentModelLike {
protected $connection = 'mysql';
protected $table = null;
protected $primaryKey = 'id';
protected $keyType = 'string';
public $incrementing = false;
protected $with = [];
protected $withCount = [];
public $preventsLazyLoading = false;
protected $perPage = 15;
public $exists = false;
public $wasRecentlyCreated = false;
protected $escapeWhenCastingToString = false;
protected $attributes = [];
protected $original = [];
protected $changes = [];
protected $previous = [];
protected $casts = [
'id' => 'string', 'metadata' => 'array', 'amount' => 'decimal:2',
'size' => 'integer', 'version' => 'integer', 'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $classCastCache = [];
protected $attributeCastCache = [];
protected $dateFormat = null;
protected $appends = [];
protected $dispatchesEvents = [];
protected $observables = [];
protected $relations = [];
protected $touches = [];
protected $relationAutoloadCallback = null;
protected $relationAutoloadContext = null;
public $timestamps = true;
public $usesUniqueIds = true;
protected $hidden = [];
protected $visible = [];
protected $fillable = [
'owner_id', 'hash', 'path', 'thumbnail_path', 'original_path', 'metadata',
'status', 'type', 'amount', 'size', 'version', 'deleted_at', 'expires_at',
'rejected_reason', 'notes', 'verified_by',
];
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $forceDeleting = false;
protected $dates = [];
protected $hashAlgo = null;
protected $pivotParent = null;
protected $morphClass = null;
protected $lockVersion = null;
protected $readOnly = false;
protected $unguarded = false;
protected $routeKeyName = null;
public function setRawAttributes(array $attributes): void {
$this->attributes = $attributes;
$this->original = $this->attributes;
$this->exists = true;
}
public function getAttributes(): array { return $this->attributes; }
public function getOriginal(): array { return $this->original; }
}
function mk_eloquent_model(int $i): EloquentModelLike {
$statuses = ['pending', 'approved', 'rejected'];
$types = ['license', 'passport', 'certificate', 'transcript'];
$id = fx_uuid7("doc$i");
$owner = fx_uuid7('owner' . ($i % 7));
$m = new EloquentModelLike();
$m->setRawAttributes([
'id' => $id,
'owner_id' => $owner,
'hash' => hash('sha256', "content$i"),
'path' => "documents/$owner/$id.pdf",
'thumbnail_path' => "thumbnails/$owner/$id.png",
'original_path' => "uploads/tmp/" . fx_hex("up$i", 20) . ".pdf",
'metadata' => json_encode([
'mime' => 'application/pdf', 'pages' => 1 + $i % 9,
'original_name' => "scan_$i.pdf", 'bytes' => 20480 + $i * 131,
]),
'status' => distinct_string($statuses[$i % 3]),
'type' => distinct_string($types[$i % 4]),
'created_at' => fx_ts($i * 3607),
'updated_at' => fx_ts($i * 3607 + 86400),
'amount' => sprintf('%d.%02d', 100 + $i * 7, $i % 100),
'size' => 20480 + $i * 131,
'version' => 1 + $i % 3,
'deleted_at' => null,
'expires_at' => null,
'rejected_reason' => null,
'notes' => null,
]);
return $m;
}
// Illuminate\Support\Collection keeps its models in a protected $items list.
class CollectionLike {
protected $items = [];
protected $escapeWhenCastingToString = false;
public function __construct(array $items) { $this->items = $items; }
public function all(): array { return $this->items; }
}
function mk_eloquent_collection(int $n): CollectionLike {
$items = [];
for ($i = 0; $i < $n; $i++) $items[] = mk_eloquent_model($i);
return new CollectionLike($items);
}
// Carbon's own __serialize() payload shape (DateTime-compatible triple).
final class CarbonLike {
public string $date;
public int $timezone_type;
public string $timezone;
public function __construct(string $date) {
$this->date = $date;
$this->timezone_type = 3;
$this->timezone = 'UTC';
}
public function __serialize(): array {
return ['date' => $this->date, 'timezone_type' => $this->timezone_type, 'timezone' => $this->timezone];
}
public function __unserialize(array $data): void {
$this->date = $data['date'];
$this->timezone_type = $data['timezone_type'];
$this->timezone = $data['timezone'];
}
}
function mk_carbon(int $offset): CarbonLike {
return new CarbonLike(fx_ts($offset) . sprintf('.%06d', (int) fmod($offset * 7919, 1000000)));
}
enum WalletGroupType: string {
case Licenses = 'licenses';
case Certifications = 'certifications';
case Education = 'education';
case Identity = 'identity';
case Employment = 'employment';
}
enum RecordStatus: string {
case Active = 'active';
case Expired = 'expired';
case Pending = 'pending';
}
enum RecordSource: string {
case Manual = 'manual';
case PrimarySource = 'primary_source';
case Import = 'import';
}
enum RecordVisibility: string {
case Private = 'private';
case Shared = 'shared';
}
enum RecordKind: int {
case License = 1;
case Certificate = 2;
case Degree = 3;
case Badge = 4;
}
final class VerificationSource {
public function __construct(
public readonly string $id,
public readonly string $name,
public readonly string $url,
public readonly RecordSource $kind,
public readonly ?CarbonLike $checkedAt,
) {}
}
final class WalletRecord {
public function __construct(
public readonly string $id,
public readonly string $walletId,
public readonly RecordKind $kind,
public readonly RecordStatus $status,
public readonly RecordSource $source,
public readonly RecordVisibility $visibility,
public readonly ?CarbonLike $issuedAt,
public readonly ?CarbonLike $expiresAt,
public readonly ?CarbonLike $verifiedAt,
public readonly array $details,
public readonly string $title,
public readonly string $issuer,
public readonly string $number,
public readonly string $country,
public readonly ?string $state,
public readonly ?string $notes,
public readonly bool $isPrimary,
public readonly bool $isVerified,
public readonly bool $isExpired,
public readonly int $sortOrder,
public readonly int $documentCount,
public readonly array $documents,
public readonly ?VerificationSource $verificationSource,
public readonly array $metadata,
public readonly array $tags,
public readonly string $createdBy,
public readonly ?float $score,
) {}
}
final class WalletGroup {
public function __construct(
public readonly WalletGroupType $type,
public readonly array $records,
public readonly array $documents,
) {}
}
// Records alternate $docsPerRecord / $docsPerRecord-1 documents; the defaults
// (10 groups x 4 records, 100 models) put the native serialize() payload at
// ~390 KB, the size class of the ~372 KB production sample. Every model is referenced twice: from its
// record and from the group's flat document list.
function mk_wallet(int $groups = 10, int $recordsPerGroup = 4, int $docsPerRecord = 3): array {
$types = WalletGroupType::cases();
$statuses = RecordStatus::cases();
$kinds = RecordKind::cases();
$walletId = fx_uuid7('wallet');
$source = new VerificationSource(
fx_uuid7('vsrc'), 'State Licensing Board', 'https://verify.example.gov/lookup',
RecordSource::PrimarySource, mk_carbon(999),
);
$out = [];
$doc = 0;
$rec = 0;
for ($g = 0; $g < $groups; $g++) {
$groupDocs = [];
$records = [];
for ($r = 0; $r < $recordsPerGroup; $r++, $rec++) {
$recDocs = [];
$docCount = $docsPerRecord - $rec % 2;
for ($d = 0; $d < $docCount; $d++, $doc++) {
$model = mk_eloquent_model($doc);
$recDocs[] = $model;
$groupDocs[] = $model;
}
$records[] = new WalletRecord(
id: fx_uuid7("rec$rec"),
walletId: $walletId,
kind: $kinds[$rec % count($kinds)],
status: $statuses[$rec % count($statuses)],
source: $rec % 2 ? RecordSource::PrimarySource : RecordSource::Manual,
visibility: $rec % 5 ? RecordVisibility::Shared : RecordVisibility::Private,
issuedAt: mk_carbon($rec * 86400),
expiresAt: $rec % 3 ? mk_carbon($rec * 86400 + 31536000) : null,
verifiedAt: $rec % 2 ? mk_carbon($rec * 86400 + 3600) : null,
details: [distinct_string('Board certified'), "Class " . chr(65 + $rec % 4), "Renewal " . (2027 + $rec % 3)],
title: "Registered Nurse License $rec",
issuer: 'State Board of Nursing',
number: sprintf('RN-%07d', 40000 + $rec * 17),
country: distinct_string('US'),
state: $rec % 4 ? distinct_string('CA') : null,
notes: $rec % 6 ? null : "Renewed after audit $rec",
isPrimary: $r === 0,
isVerified: $rec % 2 === 1,
isExpired: false,
sortOrder: $r,
documentCount: $docCount,
documents: $recDocs,
verificationSource: $rec % 2 ? $source : null,
metadata: ['imported' => false, 'rev' => $rec % 4, 'origin' => distinct_string('portal')],
tags: [],
createdBy: fx_uuid7('user' . ($rec % 3)),
score: $rec % 3 ? 0.5 + ($rec % 10) / 20 : null,
);
}
$out[] = new WalletGroup($types[$g % count($types)], $records, $groupDocs);
}
return $out;
}
enum AuditEvent: string {
case Viewed = 'viewed';
case Shared = 'shared';
case Downloaded = 'downloaded';
}
final class AuditDto {
public function __construct(
public readonly AuditEvent $event,
public readonly string $actorId,
public readonly string $subjectId,
public readonly string $tenantId,
public readonly array $context,
public readonly array $changes,
public readonly string $userAgent,
public readonly CarbonLike $occurredAt,
public readonly string $ipAddress,
public readonly string $url,
public readonly string $method,
public readonly string $requestId,
public readonly int $severity,
) {}
}
// Queue payload shape: Queueable defaults around a private readonly DTO.
final class QueueJobLike {
public $connection = null;
public $queue = null;
public $delay = null;
public $afterCommit = null;
public $middleware = [];
public $chained = [];
public $chainConnection = null;
public $chainQueue = null;
public $chainCatchCallbacks = null;
public $job = null;
public function __construct(private readonly AuditDto $dto) {}
public function dto(): AuditDto { return $this->dto; }
}
function mk_queue_job(): QueueJobLike {
$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36';
return new QueueJobLike(new AuditDto(
event: AuditEvent::Shared,
actorId: fx_uuid7('actor'),
subjectId: fx_uuid7('subject'),
tenantId: fx_uuid7('tenant'),
context: ['share_id' => fx_uuid7('share'), 'recipient' => 'hr@example.com', 'expires_in' => 604800, 'records' => 3, 'channel' => distinct_string('email')],
changes: ['status' => distinct_string('shared'), 'shared_at' => fx_ts(7200), 'count' => 4],
userAgent: distinct_string($ua),
occurredAt: mk_carbon(7200),
ipAddress: distinct_string('203.0.113.42'),
url: 'https://app.example.com/wallet/share/' . fx_hex('share', 16),
method: distinct_string('POST'),
requestId: fx_uuid7('request'),
severity: 2,
));
}
function mk_catalog(int $rows = 60): array {
$kinds = ['date', 'string', 'email', 'numeric'];
$out = [];
for ($r = 0; $r < $rows; $r++) {
$attrs = [];
$n = 10 + ($r * 7) % 16;
for ($a = 0; $a < $n; $a++) {
$validators = [];
$validators[] = 'nullable';
$validators[] = $kinds[($r + $a) % 4];
$attrs[] = [
'label' => ucfirst(str_replace('_', ' ', "field_{$a}_label")),
'name' => "field_$a",
'validators' => $validators,
'isHidden' => $a % 5 === 4,
];
}
$out[] = ['document_type' => "doc_type_$r", 'label' => "Document Type $r", 'attributes' => $attrs];
}
return $out;
}
function mk_jwks(): array {
$keys = [];
for ($k = 0; $k < 2; $k++) {
$raw = '';
for ($b = 0; strlen($raw) < 256; $b++) $raw .= hash('sha256', "modulus$k-$b", true);
$keys[] = [
'alg' => 'RS256',
'e' => 'AQAB',
'kid' => fx_hex("kid$k", 40),
'kty' => 'RSA',
'n' => rtrim(strtr(base64_encode(substr($raw, 0, 256)), '+/', '-_'), '='),
'use' => 'sig',
];
}
return ['keys' => $keys];
}
$ALL_SERIALIZERS = [
'phpser' => ['phpser_serialize', 'phpser_unserialize'],
'igbinary' => ['igbinary_serialize', 'igbinary_unserialize'],
'serialize' => ['serialize', 'unserialize'],
'msgpack' => ['msgpack_pack', 'msgpack_unpack'],
];
$SERIALIZERS = [];
foreach ($ALL_SERIALIZERS as $name => [$enc, $dec]) {
if (function_exists($enc) && function_exists($dec)) {
$SERIALIZERS[$name] = [$enc, $dec];
}
}
if (!isset($SERIALIZERS['phpser'])) {
fwrite(STDERR, "phpser extension not loaded; nothing to benchmark.\n");
exit(1);
}
$REFERENCE = isset($SERIALIZERS['igbinary']) ? 'igbinary' : 'phpser';
// Empty/zero values retain the default; other invalid counts still time a call.
$ITERS = max(1, (int) (getenv('BENCH_ITERS') ?: 1000));
$REPS = max(1, (int) (getenv('BENCH_REPS') ?: 35));
$warmup_env = getenv('BENCH_WARMUP');
// The string "0" is an explicit opt-out, not a missing environment value.
$WARMUP_ITERS = max(0, (int) (($warmup_env === false || $warmup_env === '') ? 100 : $warmup_env));
$FORMAT = match (true) {
in_array('--html', $argv, true),
in_array('--format=html', $argv, true) => 'html',
in_array('--format=json', $argv, true) => 'json',
default => 'text',
};
$ONLY_EXTENDED = in_array('--only-extended', $argv, true);
$EXTENDED = $ONLY_EXTENDED || in_array('--extended', $argv, true);
function median(array $xs): float {
sort($xs);
$n = count($xs);
$m = intdiv($n, 2);
return ($n % 2) ? $xs[$m] : ($xs[$m - 1] + $xs[$m]) / 2.0;
}
function percentile_sorted(array $sorted, float $q): float {
$n = count($sorted);
if ($n === 1) return $sorted[0];
$pos = ($n - 1) * $q;
$lo = (int) floor($pos);
$hi = (int) ceil($pos);
return $lo === $hi ? $sorted[$lo] : $sorted[$lo] + ($sorted[$hi] - $sorted[$lo]) * ($pos - $lo);
}
function iqr(array $xs): float {
sort($xs);
return percentile_sorted($xs, 0.75) - percentile_sorted($xs, 0.25);
}
function time_op_sample(callable $fn, $arg, int $iters): float {
$t = hrtime(true);
for ($i = 0; $i < $iters; $i++) {
$fn($arg);
}
return (hrtime(true) - $t) / $iters;
}
function serializer_order(array $names, int $rep): array {
$count = count($names);
if ($count < 2) return $names;
$offset = $rep % $count;
return array_merge(array_slice($names, $offset), array_slice($names, 0, $offset));
}
$cases = [
'null' => null,
'bool' => true,
'int' => PHP_INT_MIN,
'float' => 3.14159,
'string' => "hello \x00 binary",
'rowset_100' => mk_rowset(100),
'rowset_1000' => mk_rowset(1000),
'rowset_distinct_1000' => mk_rowset_distinct(1000),
'packed_1k' => mk_numeric_packed(1000),
'packed_10k' => mk_numeric_packed(10000),
'packed_rand_10k' => mk_numeric_rand(10000),
'deep_50' => mk_deep_nested(50),
'dto_100' => mk_dto_users(100),
'dto_1000' => mk_dto_users(1000),
'dto_mixed' => mk_dto_mixed(100),
];
foreach ($cases as $k => $v) {
$rt = phpser_unserialize(phpser_serialize($v));
if (serialize($rt) !== serialize($v)) {
fwrite(STDERR, "ROUND-TRIP MISMATCH: $k\n");
exit(1);
}
}
$distinctRowCount = count($cases['rowset_distinct_1000']);
for ($i = 0; $i < $distinctRowCount; $i++) {
if (ReflectionReference::fromArrayElement($cases['rowset_distinct_1000'], $i) !== null) {
fwrite(STDERR, "ROWSET DISTINCT FIXTURE CONTAINS REFERENCES\n");
exit(1);
}
}
$timed = array_filter(
$cases,
fn($k) => !in_array($k, ['null', 'bool', 'int', 'float', 'string'], true),
ARRAY_FILTER_USE_KEY
);
// A Closure case is a fixture builder: each serializer then encodes its own
// copy. Encoding an object can build its property table (igbinary_serialize()
// does on 8.4; native serialize() does not), and phpser's output for
// protected/untyped properties differs once that table exists, so a shared
// copy would measure phpser in a state that only the other columns created.
function case_data(mixed $case): mixed {
return $case instanceof Closure ? $case() : $case;
}
// $iters is either one count for every case or a per-label map.
function bench_matrix(array $cases, array $serializers, int|array $iters, int $reps, int $warmup): array {
$results = [];
foreach ($cases as $label => $case) {
$n = is_array($iters) ? $iters[$label] : $iters;
$prepared = [];
foreach ($serializers as $name => [$enc, $dec]) {
try {
$data = case_data($case);
$blob = $enc($data);
if (!is_string($blob) || $blob === '') {
throw new RuntimeException('empty payload');
}
$dec($blob); // smoke test; a throw drops this cell to n/a
$prepared[$name] = [$enc, $dec, $blob, $data];
$results[$label][$name] = [
'size' => strlen($blob),
'enc_samples' => [],
'dec_samples' => [],
];
} catch (\Throwable $e) {
$results[$label][$name] = ['err' => $e->getMessage()];
}
}
$names = array_keys($prepared);
// Untimed warmup so cold caches / first-call paths don't pollute rep 0.
if ($warmup > 0) {
foreach ($prepared as $name => [$enc, $dec, $blob, $data]) {
try {
time_op_sample($enc, $data, $warmup);
time_op_sample($dec, $blob, $warmup);
} catch (\Throwable $e) {
$results[$label][$name] = ['err' => $e->getMessage()];
}
}
}
for ($rep = 0; $rep < $reps; $rep++) {
$order = serializer_order($names, $rep);
foreach ($order as $name) {
if (isset($results[$label][$name]['err'])) continue;
[$enc, , $blob, $data] = $prepared[$name];
try {
$results[$label][$name]['enc_samples'][] =
time_op_sample($enc, $data, $n);
} catch (\Throwable $e) {
$results[$label][$name] = ['err' => $e->getMessage()];
}
}
foreach (array_reverse($order) as $name) {
if (isset($results[$label][$name]['err'])) continue;
[, $dec, $blob] = $prepared[$name];
try {
$results[$label][$name]['dec_samples'][] =
time_op_sample($dec, $blob, $n);
} catch (\Throwable $e) {
$results[$label][$name] = ['err' => $e->getMessage()];
}
}
}
foreach ($names as $name) {
if (isset($results[$label][$name]['err'])) continue;
$results[$label][$name]['enc'] = median(
$results[$label][$name]['enc_samples']);
$results[$label][$name]['dec'] = median(
$results[$label][$name]['dec_samples']);
$results[$label][$name]['enc_iqr'] = iqr(
$results[$label][$name]['enc_samples']);
$results[$label][$name]['dec_iqr'] = iqr(
$results[$label][$name]['dec_samples']);
unset(
$results[$label][$name]['enc_samples'],
$results[$label][$name]['dec_samples']
);
}
}
return $results;
}
// Picks an inner-loop count per case so one sample of the slowest serializer
// costs about $budget_ns; large app payloads would otherwise take minutes.
function calibrate_iters(array $cases, array $serializers, int $cap, float $budget_ns): array {
$out = [];
foreach ($cases as $label => $case) {
$worst = 1.0;
foreach ($serializers as [$enc, $dec]) {
try {
$data = case_data($case);
$blob = $enc($data);
$worst = max($worst, time_op_sample($enc, $data, 3), time_op_sample($dec, $blob, 3));
} catch (\Throwable) {
}
}
$out[$label] = max(min(10, $cap), min($cap, (int) ($budget_ns / $worst)));
}
return $out;
}
function hmac_frame(string $payload, string $key): string {
return hash_hmac('sha256', $payload, $key, true) . $payload;
}
function hmac_open(string $frame, string $key): string {
$payload = substr($frame, 32);
if (!hash_equals(substr($frame, 0, 32), hash_hmac('sha256', $payload, $key, true))) {
throw new RuntimeException('signature verification failed');
}
return $payload;
}
// Decodes $keep copies into a live array so every result stays reachable,
// the way a request that loads cached collections holds them. With the
// collector on, any possible roots left behind by decode fill the root buffer
// and trigger full-graph scans that the GC-off timing does not pay.
function gc_retained_sample(callable $dec, string $blob, int $keep, bool $gc_on): array {
ini_set('memory_limit', '-1');
gc_enable();
for ($i = 0; $i < 3; $i++) $dec($blob);
gc_collect_cycles();
if (!$gc_on) gc_disable();
$before = gc_status();
$bag = [];
$t = hrtime(true);
for ($i = 0; $i < $keep; $i++) $bag[] = $dec($blob);
$ns = (hrtime(true) - $t) / $keep;
$after = gc_status();
return [
'ns' => $ns,
'runs' => $after['runs'] - $before['runs'],
'collected' => $after['collected'] - $before['collected'],
'threshold' => $before['threshold'],
];
}
// The GC root threshold only ever adapts upward within a process, so a cell
// measured late would see fewer collector runs than one measured early. Each
// sample runs in a forked child of a parent that has kept the collector off,
// which starts every sample from the same threshold.
function run_isolated(callable $fn): array {
if (!function_exists('pcntl_fork')) {
try {
return $fn() + ['isolated' => false];
} catch (\Throwable $e) {
return ['err' => $e->getMessage(), 'isolated' => false];
}
}
$path = tempnam(sys_get_temp_dir(), 'phpser-bench-');
$pid = pcntl_fork();
if ($pid === -1) {
unlink($path);
throw new RuntimeException('pcntl_fork failed');
}
if ($pid === 0) {
try {
file_put_contents($path, serialize($fn()));
} catch (\Throwable $e) {
file_put_contents($path, serialize(['err' => $e->getMessage()]));
}
exit(0);
}
// A handled signal can interrupt waitpid before the child writes its result.
// Keep waiting for this child rather than reading/unlinking its file early.
do {
$waited = pcntl_waitpid($pid, $status);
} while ($waited === -1 && pcntl_get_last_error() === PCNTL_EINTR);
if ($waited === -1) {
$error = pcntl_strerror(pcntl_get_last_error());
unlink($path);
throw new RuntimeException('pcntl_waitpid failed: ' . $error);
}
$raw = file_get_contents($path);
unlink($path);
$res = $raw === '' || $raw === false ? false : unserialize($raw);
if (!is_array($res)) {
throw new RuntimeException('forked sample exited without a result');
}
// A valid result can be written before a shutdown callback fails or kills
// the child. Do not report that incomplete process as a successful sample.
if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) {
throw new RuntimeException('forked sample exited unsuccessfully');
}
return $res + ['isolated' => true];
}
function bench_gc_retained(array $cases, array $serializers, int $keep_cap, int $mem_budget, int $reps): array {
$results = [];
foreach ($cases as $label => $case) {
$blobs = [];
$bytes = 1;
foreach ($serializers as $name => [$enc, $dec]) {
try {
$blobs[$name] = $enc(case_data($case));
if (!is_string($blobs[$name]) || $blobs[$name] === '') {
throw new RuntimeException('empty payload');
}
$m0 = memory_get_usage();
$probe = $dec($blobs[$name]);
$bytes = max($bytes, memory_get_usage() - $m0);
unset($probe);
} catch (\Throwable $e) {
$results[$label][$name] = ['err' => $e->getMessage()];
}
}
$keep = max(10, min($keep_cap, intdiv($mem_budget, $bytes)));
$names = array_keys(array_diff_key($blobs, $results[$label] ?? []));
$samples = [];
for ($rep = 0; $rep < $reps; $rep++) {
foreach (serializer_order($names, $rep) as $name) {
if (isset($results[$label][$name]['err'])) continue;
$dec = $serializers[$name][1];
foreach (['gc_on' => true, 'gc_off' => false] as $mode => $on) {
try {
$sample = run_isolated(
fn() => gc_retained_sample($dec, $blobs[$name], $keep, $on));
} catch (\Throwable $e) {
// A child can exit before returning a serialized error.
$sample = ['err' => $e->getMessage()];
}
if (isset($sample['err'])) {
$results[$label][$name] = ['err' => $sample['err']];
continue 2;
}
$samples[$name][$mode][] = $sample;
}
}
}
foreach ($names as $name) {
if (isset($results[$label][$name]['err'])) continue;
$cell = ['keep' => $keep, 'isolated' => $samples[$name]['gc_on'][0]['isolated']];
foreach (['gc_on', 'gc_off'] as $mode) {
$ns = array_column($samples[$name][$mode], 'ns');
$cell[$mode] = median($ns);
$cell[$mode . '_iqr'] = iqr($ns);
}
$cell['gc_on_runs'] = median(array_column($samples[$name]['gc_on'], 'runs'));
$cell['gc_on_collected'] = median(array_column($samples[$name]['gc_on'], 'collected'));
$cell['threshold'] = $samples[$name]['gc_on'][0]['threshold'];
$results[$label][$name] = $cell;
}
}
return $results;
}
function run_extended(array $serializers, string $reference, int $iters, int $reps, int $warmup): array {
$ext_reps = max(1, (int) (getenv('BENCH_EXT_REPS') ?: min($reps, 15)));
$budget_ns = 1e6 * max(1, (int) (getenv('BENCH_EXT_SAMPLE_MS') ?: 40));
$gc_reps = max(1, (int) (getenv('BENCH_GC_REPS') ?: 5));
$gc_keep = max(10, (int) (getenv('BENCH_GC_KEEP') ?: 200));
$gc_mem = 1048576 * max(16, (int) (getenv('BENCH_GC_MEM_MB') ?: 256));
$dto_1000 = fn() => mk_dto_users(1000);
$rowset_1000 = mk_rowset(1000);
$one_dto = fn() => mk_dto_users(1)[0];
$string_15 = distinct_string('cache:user:4217');
$groups = [];
$groups['shapes'] = [
'title' => 'EXTENDED SHAPES',
'note' => 'single values, wrapped envelopes, array-sharing variants',
'reference' => $reference,
'cases' => [
'one_dto' => $one_dto,
'small_assoc' => mk_small_assoc(),
'string_15' => $string_15,
'int_single' => 1234567,
'wrapped_dto_1000' => fn() => ['data' => mk_dto_users(1000), 'ttl' => 60],
'wrapped_rowset_1000' => ['data' => $rowset_1000, 'ttl' => 60],
'rowset_tags_distinct_1000' => mk_rowset_tags_distinct(1000),
'rowset_tags_shared_1000' => mk_rowset_tags_shared(1000),
],
'serializers' => $serializers,
];
$groups['app'] = [
'title' => 'APP SHAPES',
'note' => 'Laravel-app payload shapes, dependency-free builders; reference is native serialize()',
'reference' => isset($serializers['serialize']) ? 'serialize' : $reference,
'cases' => [
'eloquent_model' => fn() => mk_eloquent_model(0),
'eloquent_coll_30' => fn() => mk_eloquent_collection(30),
'carbon_like' => fn() => mk_carbon(0),
'wallet' => fn() => mk_wallet(),
'queue_job' => fn() => mk_queue_job(),
'catalog' => fn() => mk_catalog(),