HashTable analysis in PHP kernel in PHP core technology and practice
- HashTable is the soul of PHP. because HastTable is widely used in the Zend Engine, such as variable tables, constant tables, function tables, and arrays, it is very important to understand HashTable!
- Data structure of HashTable in PHP kernel: PHP HashTable maintains a two-way linked list at the same time, and this two-way linked list is maintained through the pListNext and pListLast member variables. In member variables, pData and pDataStr are more confusing. pData points to the memory block address to be saved, which is usually allocated through system calls such as malloc, but sometimes only one pointer is saved, if you call a system call such as malloc to allocate memory, it will lead to memory fragmentation. in this case, the PHP kernel is intolerable, so the pDataPtr pointer appears. PDataPtr pointers are directly saved to pDataPtr member variables when you want to save a pointer type data, instead of calling malloc to allocate memory, thus preventing the generation of memory fragments, pData then directly points to pDataPtr. when the data to be saved is not a pointer, pDataPtr is set to NULL.
To find a data stored in HashTable, it is through the index (key), each element has an index and is different, you can find this element through the index and obtain the data stored in it. Indexes are stored in the memory of the long nKeyLength starting position of the last member arKey of HashTable. Although the arKey has only one byte, a commonly used technique (flesible array) in C language is used here ), apply for memory size of sizeof (Bucket) + nKeyLength, and save the index to the arKey member.
However, if the index is an integer, you can also treat the integer as a string, but PHP does not do this, but uses a technique to solve it. When the index is an integer, PHP saves the index to the h Member variable of the Bucket structure, and then sets nKeyLength to 0, indicating that this is an integer rather than a string. Therefore, when the nKeyLength is greater than 0, the index can be obtained in arKey, and when nKeyLength is equal to 0, the index is obtained in h. When nKeyLength is 0, isn't the h Member variable useless? Otherwise, when the nKeyLength is greater than 0 (when the index is a string), the h member stores the value after the index is processed by the hash function. the benefit of doing so is, you do not need to re-calculate the hash value of the index during re-hash. (The hash function returns an integer, so it can be saved in ulong h; and can be used as a subscript)
-
HashTable struct analysis: