Skip to content

Instantly share code, notes, and snippets.

@ivanaugustobds
Last active May 18, 2019 11:45
Show Gist options
  • Save ivanaugustobds/d3bd8e07fa966281fd1775484dec0db8 to your computer and use it in GitHub Desktop.
Save ivanaugustobds/d3bd8e07fa966281fd1775484dec0db8 to your computer and use it in GitHub Desktop.
<?php
$runBench = function ($val, Closure $callable, string $using) : array {
$startTime = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$callable($val);
}
$elapsedTime = microtime(true) - $startTime;
echo "Using $using:\t" . $elapsedTime . ' seconds' . PHP_EOL;
return compact('elapsedTime', 'using');
};
$getFastest = function (array $t1, array $t2) : string {
$fastest = $t1['elapsedTime'] < $t2['elapsedTime'] ? $t1 : $t2;
return "Fastest:\t\t{$fastest['using']}" . PHP_EOL;
};
$lb = PHP_EOL;
echo "Starting.. $lb";
// =========================
echo "{$lb}Measuring integer parse $lb";
$val = '10';
$t1 = $runBench($val, function ($val) {
return (int) $val;
}, '(int) $var');
$t2 = $runBench($val, function ($val) {
return intval($val);
}, 'intval($var)');
echo $getFastest($t1, $t2);
// =========================
echo "{$lb}Measuring float parse $lb";
$val = '99.9';
$t1 = $runBench($val, function ($val) {
return (float) $val;
}, '(float) $var');
$t2 = $runBench($val, function ($val) {
return floatval($val);
}, 'floatval($var)');
echo $getFastest($t1, $t2);
// =========================
echo "{$lb}Measuring string parse $lb";
$val = new class {
public function __toString() : string
{
return 'foo';
}
};
$t1 = $runBench($val, function ($val) {
return (string) $val;
}, '(string) $var');
$t2 = $runBench($val, function ($val) {
return strval($val);
}, 'strval($var)');
echo $getFastest($t1, $t2);
// =========================
echo "{$lb}Measuring boolean parse $lb";
$val = 'any_not_empty';
$t1 = $runBench($val, function ($val) {
return (bool) $val;
}, '(bool) $var');
$t2 = $runBench($val, function ($val) {
return boolval($val);
}, 'boolval($var)');
echo $getFastest($t1, $t2);
// =========================
echo "{$lb}Finished.$lb";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment