Created
February 20, 2015 11:03
-
-
Save ksimka/c053afed85a2cbccff29 to your computer and use it in GitHub Desktop.
`isset` is twice faster than `strlen`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on http://blog.blackfire.io/owncloud.html