Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Last active April 11, 2018 13:03
Show Gist options
  • Save KVytyagov/b66d40ec27b5166166d905891fb6a529 to your computer and use it in GitHub Desktop.
Save KVytyagov/b66d40ec27b5166166d905891fb6a529 to your computer and use it in GitHub Desktop.
Test for performance conversion variable to array with checking it's type and without it
<?php
class TestResult
{
/**
* @var int
*/
private $count;
/**
* @var float
*/
private $time;
/**
* @var int
*/
private $memPeakUsage;
/**
* TestResult constructor.
*
* @param int $count
* @param float $time
* @param int $memPeakUsage
*/
public function __construct(int $count, float $time, int $memPeakUsage)
{
$this->count = $count;
$this->time = $time;
$this->memPeakUsage = $memPeakUsage;
}
public function __toString()
{
return sprintf('iterations: %d; time: %f; memory peak: %d', $this->count, $this->time, $this->memPeakUsage);
}
/**
* @return int
*/
public function getCount(): int
{
return $this->count;
}
/**
* @return float
*/
public function getTime(): float
{
return $this->time;
}
/**
* @return int
*/
public function getMemPeakUsage(): int
{
return $this->memPeakUsage;
}
}
function doTestCheck($data, int $count): TestResult {
$start = \microtime(true);
for ($i = 0; $i < $count; ++$i) {
$temp = \is_array($data) ? $data : (array) $data;
}
$time = \microtime(true) - $start;
return new TestResult($count, $time, \memory_get_peak_usage());
}
function doTestArray($data, int $count): TestResult {
$start = \microtime(true);
for ($i = 0; $i < $count; ++$i) {
$temp = (array) $data;
}
$time = \microtime(true) - $start;
return new TestResult($count, $time, \memory_get_peak_usage());
}
$testableFuncs = [
'doTestCheck',
'doTestArray',
];
$datas = [
\range(1,10),
'string',
42,
0.42,
new stdClass(),
];
$count = 100000000;
$results = [];
foreach ($datas as $data) {
foreach ($testableFuncs as $func) {
$dataType = \gettype($data);
$result = $func($data, $count);
$results[$dataType][$func][] = $result;
echo sprintf('"%s" for "%s": %s', $func, $dataType, (string) $result) . "\n";
}
}
foreach ($results as $dataType => $classRes) {
foreach ($classRes as $class => $results) {
$count = \count($results);
$avgTime = array_sum(array_map(function (TestResult $result) {
return $result->getTime();
}, $results)) / $count;
echo \sprintf('"%s" for "%s": %f', $class, $dataType, $avgTime) . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment