string类型转int类型的三种方法速率比较
程序员文章站
2024-03-25 16:33:16
...
如果我们使用sqlite数据库,那么int类型的字段,读取出来的值会是string类型的,
比如:
id name age
1 Jame 20
php读取出来后,变成:
$arr = array(
'id' => '1',
'name' => 'Jame',
'age' => '20'
);
这时候可能就需要转换成int类型了,有三种方式(int)$val、intval($val)、$val + 0
示例代码:
<?php
$arr = ['1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1','1','1','1','1','1','1','1',
'1','1','1','1','1','1','1','1'];
$arr1 = $arr; $arr2 = $arr;
$rs = [];
list($usec, $sec) = explode(" ", microtime());
$s_time = $usec + $sec;
foreach($arr as $val)
{
foreach($arr1 as $val1)
{
foreach($arr2 as $val2)
{
$rs[] = (int)$val2;
}
}
}
list($usec, $sec) = explode(" ", microtime());
$e_time = $usec + $sec;
echo $e_time - $s_time; //输出:0.50002908706665
$rs = [];
list($usec, $sec) = explode(" ", microtime());
$s_time = $usec + $sec;
foreach($arr as $val)
{
foreach($arr1 as $val1)
{
foreach($arr2 as $val2)
{
$rs[] = $val2 + 0;
}
}
}
list($usec, $sec) = explode(" ", microtime());
$e_time = $usec + $sec;
echo '<br/>';echo $e_time - $s_time; //输出:0.46302604675293
$rs = [];
list($usec, $sec) = explode(" ", microtime());
$s_time = $usec + $sec;
foreach($arr as $val)
{
foreach($arr1 as $val1)
{
foreach($arr2 as $val2)
{
$rs[] = intval($val2);
}
}
}
list($usec, $sec) = explode(" ", microtime());
$e_time = $usec + $sec;
echo '<br/>';echo $e_time - $s_time; //输出:16.925967931747
本机windows7测试:
0.50002908706665
0.46302604675293
16.925967931747
试了很多次,结果都差不多
结论:
$val + 0 最快
(int)$val 次之
intval($val) 最慢,而且相差比较恐怖
所以建议使用(int)$val和$val + 0
上一篇: 新建HTML5文档