在给定索引的字符串中获取字符的最快方法(PHP)


Fastest way of getting a character inside a string given the index (PHP)

我知道有几种方法可以从给定索引的字符串中获取一个字符。

<?php
$string = 'abcd';
echo $string[2];
echo $string{2};
echo substr($string, 2, 1);
?>

我不知道是否有更多的方法,如果你知道任何,请不要犹豫,添加它。问题是,如果我要选择并重复一个方法超过几百万次,可能使用mt_rand来获取索引值,那么哪种方法在内存消耗最少和速度最快方面是最有效的?

要得到答案,您需要设置一个基准测试设备。在空闲机器上对所有方法进行几次(数十万或数百万)迭代的比较。尝试内置的微时间功能来测量开始和结束之间的差异。这是经过的时间。

这个测试应该花你2分钟来写。

为了节省您的工作量,我编写了一个测试。我自己的测试表明,函数解决方案(substr)要慢得多(预期)。惯用的PHP({})解决方案与index方法一样快。它们是可以互换的。([])是首选,因为这是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";
}
?>

结果:
RESULT (PHP4 &5 .习惯大括号语法): 0.19106006622314
RESULT (string slice function): 0.50699090957642

结果(*索引语法,未来作为大括号被弃用*):0.19102001190186