Speed Test: strcmp vs ===


/ Published in: PHP
Save to your folder(s)

strcmp with matching strings took 0.207852 seconds
strcmp with non-matching strings took 0.215276 seconds
=== with matching strings took 0.067122 seconds
=== with non-matching strings took 0.057305 seconds

=== is the clear winner. Function calls are always slower than operators. This was with PHP5, may be different for earlier versions. Not sure about the memory impact but I assume it's less since the strings do not have to be copied for the function call.


Copy this code and paste it in your HTML
  1. $time_start = microtime(true);
  2.  
  3. for ( $i = 0; $i < 100000; ++$i )
  4. {
  5. $results = strcmp('string' + $i, 'string' + $i);
  6. }
  7.  
  8. $time_end = microtime(true);
  9. printf("strcmp with matching strings took %f seconds\n", $time_end - $time_start);
  10.  
  11. $time_start = microtime(true);
  12.  
  13. for ( $i = 0; $i < 100000; ++$i )
  14. {
  15. $results = strcmp('string' + $i, 'string' + ($i + 1));
  16. }
  17.  
  18. $time_end = microtime(true);
  19. printf("strcmp with non-matching strings took %f seconds\n", $time_end - $time_start);
  20.  
  21. $time_start = microtime(true);
  22.  
  23. for ( $i = 0; $i < 100000; ++$i )
  24. {
  25. $results = ('string' + $i) === ('string' + $i);
  26. }
  27.  
  28. $time_end = microtime(true);
  29. printf("=== with matching strings took %f seconds\n", $time_end - $time_start);
  30.  
  31. $time_start = microtime(true);
  32.  
  33. for ( $i = 0; $i < 100000; ++$i )
  34. {
  35. $results = ('string' + $i) === ('string' + ($i + 1));
  36. }
  37.  
  38. $time_end = microtime(true);
  39. printf("=== with non-matching strings took %f seconds\n", $time_end - $time_start);

URL: http://www.mthorn.net

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.