note 77483 added to function.substr
| From: | Petez at osu1 dot php dot net | Date: | Fri, 31 Aug 2007 10:56:23 +0000 |
| Subject: | note 77483 added to function.substr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129929@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 83.138.144.80
Probable Submitter: 81.86.160.116
----
Manual Page -- http://www.php.net/manual/en/function.substr.php
Edit -- https://master.php.net/note/edit/77483
Del: integrated -- https://master.php.net/note/delete/77483/integrated
Del: useless -- https://master.php.net/note/delete/77483/useless
Del: bad code -- https://master.php.net/note/delete/77483/bad+code
Del: spam -- https://master.php.net/note/delete/77483/spam
Del: non-english -- https://master.php.net/note/delete/77483/non-english
Del: in docs -- https://master.php.net/note/delete/77483/in+docs
Del: other reasons-- https://master.php.net/note/delete/77483
Reject -- https://master.php.net/note/reject/77483
Search -- https://master.php.net/manage/user-notes.php