我知道有几种方法可以在给定索引的情况下从字符串中获取字符.
<?php
$string = 'abcd';
echo $string[2];
echo $string{2};
echo substr($string, 2, 1);
?>
Run Code Online (Sandbox Code Playgroud)
我不知道是否有更多的方法,如果您知道任何方式请不要犹豫,添加它.问题是,如果我选择并重复上述方法几百万次,可能使用mt_rand来获取索引值,哪种方法在最小内存消耗和最快速度方面最有效?
pes*_*669 18
要得出答案,您需要设置基准测试平台.比较空闲盒上几次(几十万或几百万)次迭代的所有方法.尝试使用内置的microtime功能来测量开始和结束之间的差异.那是你经过的时间.
测试应该花费你2分钟的时间来写.
为了省你一些努力,我写了一个测试.我自己的测试显示功能解决方案(substr)慢得多(预期).惯用的PHP({})解决方案与索引方法一样快.它们是可以互换的.([])是首选,因为这是PHP关于字符串偏移的方向.
<?php
$string = 'abcd';
$limit = 1000000;
$r = array(); // results
// PHP idiomatic string index method
$s = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
$c = $string{2};
}
$r[] = microtime(true) - $s;
echo "\n";
// PHP functional solution
$s = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
$c = substr($string, 2, 1);
}
$r[] = microtime(true) - $s;
echo "\n";
// index method
$s = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
$c = $string[2];
}
$r[] = microtime(true) - $s;
echo "\n";
// RESULTS
foreach ($r as $i => $v) {
echo "RESULT ($i): $v \n";
}
?>
Run Code Online (Sandbox Code Playgroud)
结果:
RESULT(PHP4和5惯用语法):0.19106006622314
RESULT(字符串切片函数):0.50699090957642
RESULT(*索引语法,未来作为大括号被弃用*):0.19102001190186
| 归档时间: |
|
| 查看次数: |
8816 次 |
| 最近记录: |