HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP substr slow?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
substrphpslow

Problem

If I have a long string:

// 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

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.