Is it bad for performance to retrieve variables from an array?
I learned about a big function extract
in PHP and I think it is really handy. However, I found out that most of the things that are good about PHP also affect performance, so my question is, what impact on usage extract
can be seen from a performance perspective?
Isn't it necessary to use outta-arrays for large applications to retrieve variables?
a source to share
Update
As the commenter noted below, and as I am now acutely aware years later - php variables are copied on write. Collecting globally will , however, keep the variables from being garbage collected. So, as I said before, "consider your volume"
Depending on the size of the array and the area where you are retrieving it, say you are retrieving a huge array into the global namespace, I could see that this has an effect since you will have all this data in memory twice - I believe though this can do some fun internal things that PHP is known to do to constrain this -
but tell me what you did
function bob(){
extract( array( 'a' => 'woo', 'b' =>'fun', 'c' => 'array' ) );
}
it will have no real effect.
In short, just consider what you are doing, why you are doing it, and the area.
a source to share
Arrays are much better in most languages because the compiler and / or interpreter can use SIMD with instructions.
You may also notice that some part of your code is trying to call one function for each value in the array. From a performance point of view, it is more efficient to call the function only once with all packed values. The overhead of a function call increases several times if the array is too long and makes it difficult to detect possible optimizations.
a source to share
I once had to debug a script that crashes; it turns out PHP is running out of memory.
Part of the problem was that it was extract()
used in a loop of 25000 elements. It would only exhaust about 2300 items before running out of memory. I replaced the fetch (associative array of 4 elements) manually by setting the variables and the loop was able to go through about 5200 entries.
So, it extract()
has certain performance disadvantages.
a source to share