php 递归替换,PHP-以递归方式将字符串替换为数字花费的时间太长

因为强制 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毫秒

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值