问题
I've started to learn PHP SPL from ArrayIterators and I'd like to know what are the benefits of using SPL ArrayObject, ArrayIterator, RecursiveArrayIterator instead of regular arrays?
a) I've heard that loops using SPL iterators will reduce memory usage (but why?). I don't really know to believe this or no because I don't understand how can it reduce memory usage.
b) Talking about RecursiveArrayIterator we can say that sometimes it could save some lines of code (we're using one foreach construction instead of 2+ (depends on array dimension)).
Probably, my questions could seem to be very easy for somebody, but there are too little information/documentation about SPL.
Thank you
回答1:
The primary benefit you're looking at efficient data access mostly in the area of readability. This way you can use object just like an array in a foreach so a closer interaction with PHP.
a) The way you reduce memory usage is by not making a copy of the array but if done properly in the engine then it should be a new reference until the array is modified then it's actually copied.
b) Essentially
A good example of this would be the SimpleXML extension. The PHP/XML object you're interacting with also acts like an array which makes it efficient to use because you can just foreach or access one of the elements within the list. You don't have to grab an array from the object and then iterate over and do something else with it if you want the tag name or an attribute.
来源:https://stackoverflow.com/questions/4072927/what-are-the-benefits-of-using-spl-arrayobject-arrayiterator-recursivearrayite