因为强制 used to be faster than casting,所以我运行了这段代码来计算PHP 7上的计时:
function getTime($start) {
return round((microtime(true) - $start) * 1000000) / 1000;
}
function mockData($length) {
$data = [];
$i = -1;
while ($i++ < $length) {
$data[$i] = strval(rand(1, 10000) / 100);
}
return $data;
}
$data = mockData(100000);
// Let's check that they are string before
echo gettype($data[0]) . '
';
$start = microtime(true);
$convertedData = [];
foreach ($data as $key => $value) {
$convertedData[$key] = (double) $value;
}
echo '(double) cast took ' . getTime($start) . ' ms.
';
$start = microtime(true);
$convertedData = [];
foreach ($data as $key => $value) {
$convertedData[$key] = 0 + $value;
}
echo 'Coercion took ' . getTime($start) . ' ms.
';
我的结果是:
(double) cast took 27.508 ms.
Coercion took 28.789 ms.
结论
由于使用floatval(实现字符串到双精度转换的第三种方法)的时间更长,因此使用PHP不能做得更好.您要实现的是脚本操作,不应将其用作Web应用程序的常规后端操作.
但是,如果您仍然想这样做,可以在php.ini文件as long as you don’t use the -1 workaround中提高memory_limit的值.
更新
我忘记了一种可能的优化,您应该pass your variable by reference至少执行立即分配:
$start = microtime(true);
foreach ($data as $key => $value) {
$data[$key] = (double) $value;
}
echo getTime($start) . ' ms.
';
=> 34.018毫秒
$start = microtime(true);
foreach ($data as &$value) {
$value = (double) $value;
}
echo getTime($start) . ' ms.
';
=> 17.081毫秒
显然,通过引用使用强制会产生更好的结果:
$start = microtime(true);
foreach ($data as &$value) {
$value = 0 + $value;
}
echo getTime($start) . ' ms.
';
=> 13.1毫秒