patternphpMinor
PHP substr slow?
Viewed 0 times
substrphpslow
Problem
If I have a long string:
Then I perform many
It is VERY slow (20 seconds), which I tracked down to:
How can this be optimized, without incrementing the
EDIT: for those who are upset, the reason why I don't want to use an offset is because this would require keeping the entire string in memory the whole time. I'm trying to optimize both speed and memory.
// 10MB string
$string='';
for($run=0; $run<1000000; $run++)
$string.='012345689';Then I perform many
substr, cutting off small portions from the beginning.for($run=0; $run<100000; $run++)
{
$temp=substr($string,0,10);
DoSomething($temp);
$string=substr($string,10);
}It is VERY slow (20 seconds), which I tracked down to:
substr($string,10) as the cause of the problem. Seems it is rebuilding the entire variable each time, which slowing the whole script down.How can this be optimized, without incrementing the
start offset of the first substr in the second code fragment?EDIT: for those who are upset, the reason why I don't want to use an offset is because this would require keeping the entire string in memory the whole time. I'm trying to optimize both speed and memory.
Solution
Use
You trade RAM for performance: The original string will not become shorter, but you don't need the very expensive copying of the string again and again
for($run=0; $run<100000; $run++)
{
$temp=substr($string,$run*10,10);
DoSomething($temp);
//$string=substr($string,10);
}You trade RAM for performance: The original string will not become shorter, but you don't need the very expensive copying of the string again and again
Code Snippets
for($run=0; $run<100000; $run++)
{
$temp=substr($string,$run*10,10);
DoSomething($temp);
//$string=substr($string,10);
}Context
StackExchange Code Review Q#7220, answer score: 4
Revisions (0)
No revisions yet.