How are associative arrays implemented in PHP?

瘦欲@ 提交于 2019-12-17 07:24:08

问题


Can someone explain how PHP implements associative arrays? What underlying data structure does PHP use? Does PHP hash the key and store it in some kind of hash map? I am curious because I was wondering what the performance of associative arrays where when inserting and searching for keys.


回答1:


It's a hash table. The type declaration and hashing function are here:
http://svn.php.net/viewvc/php/php-src/trunk/Zend/zend_hash.h?view=markup

There is a light weight array and a linked list within the spl (standard php lib)




回答2:


Well, for what it is worth, all PHP arrays are Associative arrays.




回答3:


The highest voted answer link is broken and doesn't give that much explanation.

PHP is written in C and the underlying structure is just a C array. C arrays are just chunks of memory. The indexes in C arrays must be continuous, you can't have an index 0 and an index 1000 that comes after it. To make associative array keys work, before they are added to the C array, they are converted to proper C indices via a hash function.

For a full explanation, I found this link to be much more informative.

http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html




回答4:


@EBGreen is correct.

Which gives you some interesting performance problems, especially when treating an array as a list and using the [] (array add) operator. PHP doesn't seem to cache the largest numeric key and add one to it, instead it seems to traverse all of the keys to find what the next numeric key should be. I've rewritten scripts in python because of PHP's dismal array-as-a-list performance.

Associative arrays have the standard dict/hash performance overhead.




回答5:


It's all hash tables, according to sources in various web forums: http://www.usenet-forums.com/php-language/15348-zend-engine-array-implementation.html

If you want to be sure, read the source, then compile it, but make sure you can trust your compiler (Warning: PDF, and unrelated, but very cool).



来源:https://stackoverflow.com/questions/247467/how-are-associative-arrays-implemented-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!