array_merge() is damn Slow

After this mornings performance by array_merge(), I doubt I would dare to use it again. What I was doing was pretty simple. My code was reading a textfile with the first one million primes. Each line had 8 primes and there were 125002 lines. I was extracting the primes eight-at-a-time and merging them with an array. This merge operation, as you can guess, was happening through array_merge() :


$primes = array();
while ($data = fscanf($fp, ' %d %d %d %d %d %d %d %d \n'))
{
$primes = array_merge($primes, $data);
}

Now can you guess how long it took to extract all the primes? I can't! Because after waiting for fifteen minutes, all the time looking at TOP, I lost patience and hit Ctrl-C. And then I changed the code to this:


$primes = array();
while ($data = fscanf($fp, ' %d %d %d %d %d %d %d %d \n'))
{
$primes[] = $data[0];
$primes[] = $data[1];
$primes[] = $data[2];
$primes[] = $data[3];
$primes[] = $data[4];
$primes[] = $data[5];
$primes[] = $data[6];
$primes[] = $data[7];
}

Now try to guess how long it took. I failed again!!! Because programme execution ended so quickly that I couldn't believe it really happened !!!@#~! It probably ended below 5 seconds.

Think about it again. 5 seconds versus 15 MINUTES plus. I know some functions are inefficient, but this much? This is really unbelievable.