Is it bad for performance to extract variables from an array?
I have found out about the great extract
function in PHP and I think that it is really handy. However I have learn that most things that are nice in PHP also affects performance, so my question is which affect using the extra开发者_StackOverflow社区ct
can have, seen in a performance perspective?
Is it a no-no to use for big applications to extract variables outta arrays?
Update:
As the commenter below noted and as I am now keenly aware years later - php variables are copy on write. Extracting in the global scope will however keep the variables from being garbage collected. So as I said before, "consider your scope"
Depends on the size of the array and the scope to which your extracting it, say you extract a huge array to the global namespace, I could see that having an effect, as you will have all that data in memory twice - I believe though it may do some fun internal stuff which PHP is known to do to limit that -
but say you did
function bob(){
extract( array( 'a' => 'woo', 'b' =>'fun', 'c' => 'array' ) );
}
its going to have no real lasting effect.
Long story short, just consider what you're doing, why your doing it, and the scope.
extract
shouldn't be used on untrusted data. And it isn't usually useful for trusted data (because there are likely a limited number of known array keys).
I don't see why it should be such a big performance hit, as long as you don't extract huge arrays in big loops. But I've never found a reason to use extract either :)
Working with arrays in most languages is far better because the compiler and/or interpreter can use SIMD instructions with it.
Also you might notice if some part of your code tries to call one function for each value within the array. From a performance point of view it is more efficient to call the function only once with all the values packed. The overhead of calling a function several times will scale up if the array is too long and makes harder to detect possible optimizations
I once had to debug a script which was crashing; it turns out that PHP was running out of memory.
Part of the problem was that extract()
was being used in a loop of 25000 elements. It would only get through about 2300 elements before running out of memory. I replaced the extract (associative array of 4 elements) with manually setting the variables, and the loop was able to get through about 5200 records.
So extract()
definitely has performance drawbacks.
精彩评论