简体   繁体   中英

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

I know of several ways to get a character off a string given the index.

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

I don't know if there are any more ways, if you know of any please don't hesitate to add it. The question is, if I were to choose and repeat a method above a couple of million times, possibly using mt_rand to get the index value, which method would be the most efficient in terms of least memory consumption and fastest speed?

To arrive at an answer, you'll need to setup a benchmark test rig. Compare all methods over several (hundreds of thousands or millions) iterations on an idle box. Try the built-in microtime function to measure the difference between start and finish. That's your elapsed time.

The test should take you all of 2 minutes to write.

To save you some effort, I wrote a test. My own test shows that the functional solution (substr) is MUCH slower (expected). The idiomatic PHP ({}) solution is as fast as the index method. They are interchangeable. The ([]) is preferred, as this is the direction where PHP is going regarding string offsets.

<?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";
}
?>

Results:
RESULT ( PHP4 & 5 idiomatic braces syntax ): 0.19106006622314
RESULT ( string slice function ): 0.50699090957642
RESULT (*index syntax, the future as the braces are being deprecated *): 0.19102001190186

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM