The fastest way to get a character inside a string based on index (PHP)

I know several ways to get a character from a string given an index.

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

I don’t know if there are any other ways, if you know, please feel free to add it. The question is, should I select and repeat the method above several million times, perhaps using mt_rand to get the index value, which method will be most effective in terms of least memory consumption and fast speed?

+5
source share
1 answer

, . ( ) . 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";
}
?>

:
( PHP4 5): 0.19106006622314
( ): 0.50699090957642
(* , , *): 0.19102001190186

+18

All Articles