fork download
  1. <?php
  2.  
  3. class User {}
  4. class Contact {}
  5.  
  6. class MyClass {
  7.  
  8. private $handler;
  9.  
  10. public function setHandlerWithoutCheck($function) {
  11. $this->handler = $function;
  12. }
  13.  
  14. public function setHandlerWithCheck($function) {
  15. try {
  16. $r = new ReflectionFunction($function);
  17. } catch (ReflectionException $e) {
  18. throw new InvalidArgumentException('Invalid callback passed.');
  19. }
  20. if ($r->getNumberOfParameters() !== 2) {
  21. throw new InvalidArgumentException('The callback must have exactly 2 arguments.');
  22. }
  23. static $d = array('User', 'Contact');
  24. foreach ($r->getParameters() as $i => $p) {
  25. if (!$c = $p->getClass() or strcasecmp($c->getName(), $d[$i])) {
  26. throw new InvalidArgumentException(sprintf(
  27. 'The argument #%d must have type hinting: %s',
  28. $i + 1,
  29. $d[$i]
  30. ));
  31. }
  32. }
  33. $this->handler = $function;
  34. }
  35.  
  36. }
  37.  
  38. $obj = new MyClass;
  39. $handler = function (User $user, Contact $contact) {};
  40. $max = 100000;
  41. $without = 0.0;
  42. $with = 0.0;
  43. for ($i = 0; $i < $max; ++$i) {
  44. $a = microtime(true);
  45. $obj->setHandlerWithoutCheck($handler);
  46. $b = microtime(true);
  47. $without += $b - $a;
  48. unset($a, $b);
  49. }
  50. for ($i = 0; $i < $max; ++$i) {
  51. $a = microtime(true);
  52. $obj->setHandlerWithCheck($handler);
  53. $b = microtime(true);
  54. $with += $b - $a;
  55. unset($a, $b);
  56. }
  57. printf("without check... sum:%f ave:%f\n", $without, $without / $max);
  58. printf(" with check... sum:%f ave:%f\n", $with, $with / $max);
Success #stdin #stdout 1.26s 20568KB
stdin
Standard input is empty
stdout
without check... sum:0.083990 ave:0.000001
   with check... sum:0.993105 ave:0.000010