Posts Tagged ‘Linux’

Benchmarking SPLFixedArray access speed

Friday, June 5th, 2009

Following a talk at PHPLondon on the SPL library last month I decided to play about with SPL. I was curious as to the difference in speed between SplFixedArray and a normal array particularly when it came to reading from the array.

So I initialized an array of 100,000 elements – I then timed how long it took to access each element in the array, in order. I did this 100 times and took the amount of memory used (as recorded by memory_get_peak_usage) and the total time taken. The benchmarks were done on PHP 5.3 RC2 under Linux (Kernel 2.6)  on a Intel Core 2 Duo 1.83Ghz.

The following were my compile options

CXXFLAGS=”-O3 -fomit-frame-pointer” ‘./configure’ ‘–enable-zip’ ‘–with-mysql=mysqlnd’ ‘–enable-sockets’ ‘–with-mm’ ‘–with-gd’ ‘–with-gmp’ ‘–with-jpeg-dir’ ‘–with-png-dir’ ‘–with-mcrypt’ ‘–with-curl’ ‘–with-openssl’ ‘–with-freetype-dir’ ‘–enable-calendar’ ‘–enable-mbstring’ ‘–enable-exif’ ‘–enable-ftp’ ‘–prefix=/opt/php’ ‘–with-zlib’ ‘–with-bz2′

And now for the results which are quite surprising

CPU time in seconds - SPL vs Normal PHP array

CPU time in seconds - SPL vs Normal PHP array

Memory KB Time Taken (sec)
SPL Non-SPL SPL Non-SPL
Reading using [] 31570 74729 25.28 25.49
Reading using iterator 32000 75008 19.77 13.85
Writing 36096 75008 39.60 55.17
count() 32000 75008 52.37 47.45
sizeof() 32000 75008 51.25 47.21

So it appears that SPL array is faster than a standard array  – by about 0.9% for reads. The SplFixedArray also uses 1/2 the memory of a standard PHP array which is a handy memory saving. SPL fixed arrays are much quicker  to write to compared to standard arrays by about 39%

Both the sizeof and count functions are slower with SPL. However if you have set the size of the array (as you must with a SplFixedArray) then you shouldn’t need to use these. Surprisingly using the iterator is also slower but overall SPL does seem a lot more memory efficient.

So it would seem that SplFixedArrays aren’t good for everything. It’s all swings and roundabouts and you lose flexability in order to gain speed on certain operators. So don’t go replacing all of your arrays with SPL but it’s worth remembering that they are there should you need them.