Skip to content

Instantly share code, notes, and snippets.

@totten
Created May 4, 2013 19:05
Show Gist options
  • Save totten/5518406 to your computer and use it in GitHub Desktop.
Save totten/5518406 to your computer and use it in GitHub Desktop.
Compare performance of checking for existence 10,000 times using (a) function_exists or (b) a data structure cached in DB
<?php
civicrm_initialize();
$a = microtime(TRUE);
function_exists('abc');
$b = microtime(TRUE);
for ($i = 0; $i < 10000; $i++) {
function_exists("abc_$i");
}
$c = microtime(TRUE);
// a reasonably large serialized structure
$settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Spec', 'All', NULL);
$d = microtime(TRUE);
for ($i = 0; $i < 10000; $i++) {
// isset() seems slightly faster than !empty()
if (isset($settingsMetadata["abc_$i"])) {
print "iteration $i\n"; // never actually prints, but we do the if() check 10k times
}
}
$e = microtime(TRUE);
printf("%-35s: %.10f\n", 'a=>b: function_exists (1)', $b-$a);
printf("%-35s: %.10f\n", 'b=>c: function_exists (10k)', $c-$b);
printf("%-35s: %.10f\n", 'b=>c: function_exists (10k/10k)', ($c-$b) / 10000);
printf("%-35s: %.10f\n", 'c=>d: cache fetch', $d-$c);
printf("%-35s: %.10f\n", 'c=>d: cache check (10k)', $e-$d);
printf("%-35s: %.10f\n", 'c=>d: cache check (10k/10k)', ($e-$d) / 10000);
printf("%-35s: %.10f\n", 'c=>d: cache fetch+check (10k)', $e-$c);
printf("%-35s: %.10f\n", 'c=>d: cache fetch+check (10k/10k)', ($e-$c) / 10000);
/* Output on mylaptop:
a=>b: function_exists (1) : 0.0000028610
b=>c: function_exists (10k) : 0.0116860867
b=>c: function_exists (10k/10k) : 0.0000011686
c=>d: cache fetch : 0.0022399426
c=>d: cache check (10k) : 0.0058488846
c=>d: cache check (10k/10k) : 0.0000005849
c=>d: cache fetch+check (10k) : 0.0080888271
c=>d: cache fetch+check (10k/10k) : 0.0000008089
*/
@arunbasillal
Copy link

I think line 46 and 47 should be e=>d. Isn't it so?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment