-1

Everyone says SplFixedArray is faster than array() but...

<?php 
$max_el = 256;

$a = array(); 
$c = new SplFixedArray($max_el); 
for ($i = 0; $i < $max_el; $i++) { 
   $a[$i] = $c[$i] = mt_rand(0, 1000); 
} 

$start = microtime(true); 
for ($j = 0; $j < 100000; $j++) {
   for ($i = 0; $i < $max_el; $i++) { 
      $x = $a[$i]; 
   } 
} 
$elapsed0 = microtime(true) - $start; 

$start = microtime(true); 
for ($j = 0; $j < 100000; $j++) { 
   for ($i = 0; $i < $max_el; $i++) { 
      $x = $c[$i]; 
   } 
} 
$elapsed2 = microtime(true) - $start; 

echo "Elapsed time: $elapsed0\r\n"; 
echo "Elapsed time: $elapsed2";

The output of that is as follows:

Elapsed time: 1.3631780147552
Elapsed time: 2.0408799648285

So with 256 elements array() seems faster.

Here are my results with 1024 elements:

Elapsed time: 5.6066889762878
Elapsed time: 7.7747831344604

Another win for array().

With 10*1024 elements:

Elapsed time: 57.000520944595
Elapsed time: 88.719652891159

Props, once again, for array().

When, exactly, is SplFixedArray() supposed to be faster?

Community
  • 1
  • 1
neubert
  • 15,947
  • 24
  • 120
  • 212
  • your benchmark is wrong as a per not considering CPU, memory and cache that are going underneath the running code. You should also consider to run 2 different processes for have a better benchmark, The GC could be kicked in too. Also looping 10000 times always the same reading operation is higly cached and not sure is a real world scenario neither. Please also include the assignment phase that you are combinging togheter to be benchmark. – Raffaello Aug 23 '19 at 15:30

1 Answers1

1

The page that's linked to in the earlier thread that you mentioned seems to talk mostly about write times and memory usage. Here, you're only looking at read times.

barfaroni
  • 11
  • 1