Skip to content

Instantly share code, notes, and snippets.

@ksimka
Created February 20, 2015 11:03
Show Gist options
  • Save ksimka/c053afed85a2cbccff29 to your computer and use it in GitHub Desktop.
Save ksimka/c053afed85a2cbccff29 to your computer and use it in GitHub Desktop.
`isset` is twice faster than `strlen`
<?php
$strs = [];
$s = str_repeat("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10);
$n = 100000;
for ($i = 0; $i < $n; $i++) {
$strs[$i] = substr(str_shuffle($s), 0, mt_rand(10, 100));
}
$t1 = $t2 = 0;
$start = microtime(1);
$c1 = 0;
for ($i = 0; $i < $n; $i++) {
if (strlen($strs[$i]) > 60) {
$c1++;
}
}
$t1 = microtime(1) - $start;
$start = microtime(1);
$c2 = 0;
for ($i = 0; $i < $n; $i++) {
if (isset($strs[$i][60])) {
$c2++;
}
}
$t2 = microtime(1) - $start;
echo "isset: {$t2} ({$c2})\nstrlen: {$t1} ({$c1})\n";
// 3 runs:
// ------
// isset: 0.060104131698608 (44030)
// strlen: 0.13449788093567 (44030)
//
// isset: 0.058434963226318 (44055)
// strlen: 0.13221907615662 (44055)
//
// isset: 0.060664176940918 (43928)
// strlen: 0.14264702796936 (43928)
@ksimka
Copy link
Author

ksimka commented Feb 20, 2015

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