Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. <?php
  2.  
  3. function try_json_encode($data)
  4. {
  5. json_encode($data);
  6. return (json_last_error() == JSON_ERROR_NONE);
  7. }
  8.  
  9. function json_encode_type_check($data)
  10. {
  11. static $validTypes = [
  12. 'string' => true,
  13. 'integer' => true,
  14. 'double' => true,
  15. 'boolean' => true,
  16. 'array' => true,
  17. 'null' => true,
  18. ];
  19.  
  20. $type = gettype($data);
  21.  
  22. return isset($validTypes[$type])
  23. || $type == 'object' and $data instanceof JsonSerializable;
  24. }
  25.  
  26. function benchmark($f, $iterations, ...$args)
  27. {
  28. $startTime = microtime(true);
  29. for ($i = 0; $i < $iterations; $i++) {
  30. $f(...$args);
  31. }
  32. return ((microtime(true) - $startTime) / $iterations) * 1e9;
  33. }
  34.  
  35. $iterations = 10000;
  36.  
  37. $cases = [
  38. 'associative' => ['foo' => ['bar', 'baz', ['bam' => false]]],
  39. 'boolean' => true,
  40. 'string' => 'foobaz',
  41. 'number' => -1,
  42. 'deep assoc' => ['foo' => ['bar', 'baz', ['bam' => false]], ['foo' => ['bar', 'baz', ['bam' => false]]]],
  43. ];
  44.  
  45. $benches = ['try_json_encode', 'json_encode_type_check'];
  46. foreach ($cases as $caseName => $case) {
  47. foreach ($benches as $bench) {
  48. $result = benchmark($bench, $iterations, $case);
  49. printf("%-20s %-30s: %-20f ns/iter\n", $caseName, $bench, $result);
  50. }
  51. echo "----\n";
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement