MediaWiki master
benchmarkJsonCodec.php
Go to the documentation of this file.
1<?php
22
23require_once __DIR__ . '/../includes/Benchmarker.php';
24
29 protected $defaultCount = 100;
30
31 public function __construct() {
32 parent::__construct();
33 $this->addDescription( 'Benchmarks JsonCodec.' );
34 $this->addOption(
35 'file',
36 'A json file, or a php file that returns a data structure. Default is config-schema.php',
37 false,
38 true
39 );
40 $this->addOption(
41 'assoc',
42 'Whether JSON objects should be represented as associative arrays when loading'
43 );
44 }
45
46 public function execute() {
47 $file = $this->getOption( 'file', MW_INSTALL_PATH . '/includes/config-schema.php' );
48 $data = $this->loadData( $file );
49 $bytes = json_encode( $data );
50
51 $codec = new JsonCodec();
52
53 $this->bench( [
54 "JsonCodec::serialize ($file)" => [
55 'function' => static function ( JsonCodec $codec, $data ) {
56 $codec->serialize( $data );
57 },
58 'args' => [ $codec, $data ]
59 ],
60 "JsonCodec::unserialize ($file)" => [
61 'function' => static function ( JsonCodec $codec, $bytes ) {
62 $codec->unserialize( $bytes );
63 },
64 'args' => [ $codec, $bytes ]
65 ],
66 "JsonCodec::detectNonSerializableData ($file)" => [
67 'function' => static function ( JsonCodec $codec, $data ) {
68 $codec->detectNonSerializableData( $data );
69 },
70 'args' => [ $codec, $data ]
71 ],
72 ] );
73 }
74
75 private function loadData( $file ) {
76 if ( str_ends_with( $file, '.php' ) ) {
77 $data = include $file;
78 if ( !$data ) {
79 $this->fatalError( "Failed to load data from " . $file );
80 }
81 return $data;
82 }
83
84 $raw = $this->loadFile( $file );
85 $data = json_decode( $raw, $this->getOption( 'assoc', false ) );
86
87 if ( !$data ) {
88 $this->fatalError( "Failed to load data from " . $file );
89 }
90
91 return $data;
92 }
93}
94
95$maintClass = BenchmarkJsonCodec::class;
96require_once RUN_MAINTENANCE_IF_MAIN;
execute()
Do the actual work.
__construct()
Default constructor.
Base class for benchmark scripts.
bench(array $benchs)
loadFile( $file)
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
detectNonSerializableData( $value, bool $expectUnserialize=false)
Checks if the $value is JSON-serializable (contains only scalar values) and returns a JSON-path to th...
serialize( $value)
Encode $value as JSON with an intent to use JsonUnserializer::unserialize to decode it back.
unserialize( $json, string $expectedClass=null)
Restore an instance of simple type or JsonUnserializable subclass from the JSON serialization.
Definition JsonCodec.php:40