Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function try_json_encode($data)
- {
- json_encode($data);
- return (json_last_error() == JSON_ERROR_NONE);
- }
- function json_encode_type_check($data)
- {
- static $validTypes = [
- 'string' => true,
- 'integer' => true,
- 'double' => true,
- 'boolean' => true,
- 'array' => true,
- 'null' => true,
- ];
- $type = gettype($data);
- return isset($validTypes[$type])
- || $type == 'object' and $data instanceof JsonSerializable;
- }
- function benchmark($f, $iterations, ...$args)
- {
- $startTime = microtime(true);
- for ($i = 0; $i < $iterations; $i++) {
- $f(...$args);
- }
- return ((microtime(true) - $startTime) / $iterations) * 1e9;
- }
- $iterations = 10000;
- $cases = [
- 'associative' => ['foo' => ['bar', 'baz', ['bam' => false]]],
- 'boolean' => true,
- 'string' => 'foobaz',
- 'number' => -1,
- 'deep assoc' => ['foo' => ['bar', 'baz', ['bam' => false]], ['foo' => ['bar', 'baz', ['bam' => false]]]],
- ];
- $benches = ['try_json_encode', 'json_encode_type_check'];
- foreach ($cases as $caseName => $case) {
- foreach ($benches as $bench) {
- $result = benchmark($bench, $iterations, $case);
- printf("%-20s %-30s: %-20f ns/iter\n", $caseName, $bench, $result);
- }
- echo "----\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement