Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SPL, is it worth using or raw array functions are better?

Tags:

php

spl

I'm examining the Standard PHP Library (SPL). I used only arrays before and just now found that PHP has so many standard classes. But there is no any words in the manual whether it is recommended to use it or not. For example, they explicitly recommend to use foreach construction to iterate arrays because it is faster. And what about this library? If I need to store some data in an object should I use some concrete SPL class for my situation or using standard arrays is better anyway?

like image 304
Green Avatar asked Jul 07 '12 22:07

Green


1 Answers

There's a lot to your question. Should you use the SPL data structures? It depends.

The PHP array can act as a map, a linked list, or an array. Very rarely do you actually want a single data type that acts as all of those things at the same time, so the focused nature of the SPL data types are not so limiting. In fact, most "outsiders" (and some "insiders") would consider PHP's array a travesty.

The main drawback to PHP's array is that it uses a lot of memory. Even if you just want a fixed, sequential, indexed array, you have the overhead of things being linked together and storage for the keys. Despite that, PHP's array is usually much faster than object types if you are mostly appending data and iterating over it, probably because function calls slow things down.

Generally, I don't see many people use the SPL data structures. Mostly, I think, because in the context of PHP and web applications they are generally not very applicable. You are usually dealing with small arrays, where the convenience of built in operators and the array functions outweighs any advantages of the SPL types.

That said:

  • If you find yourself in a situation where you are using an array as a linked list (inserting / deleting in the middle), then try one of the SPL doubly linked lists.

  • If you find yourself using a large indexed array, try a SPLFixedArray. They will definitely consume much less memory.

  • If you need to have map with objects as the key, then use a SplObjectStorage (as the PHP array doesn't work with object keys).

  • If you want to keep data ordered in an array, try one of the heaps.

Benchmark the native array vs the SPL object and use whichever one has the memory + speed + simplicity tradeoff that suits you.

like image 74
Matthew Avatar answered Oct 24 '22 23:10

Matthew