Voting

: six plus three?
(Example: nine)

The Note You're Voting On

Petez
17 years ago
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
$opening = substr($string,0,11);
if (
$opening == 'Lorem ipsum'){
true;
}else{
false;
}
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
if (
$string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
true;
}else{
false;
}
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
$opening = strstr($string,'Lorem ipsum');
if (
$opening == true){
true;
}else{
false;
}
}
$endtime3 = endTimer();

echo
$endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.

<< Back to user notes page

To Top