Home > Backend Development > PHP Tutorial > huaidanshizenyanglianchengde Array implemented by hash in PHP

huaidanshizenyanglianchengde Array implemented by hash in PHP

WBOY
Release: 2016-07-29 08:46:10
Original
1174 people have browsed it

Array is the most used one in PHP. So how is Array implemented? In PHP, Array is implemented through a hashtable, in which the chaining method is used to solve the hash conflict problem. In this way, the complexity of finding Array elements is O(N) in the worst case, and 1 in the best case.
And it calculates the string The hash value method is as follows, extract the source code for reference:

Copy the code The code is as follows:


static inline ulong zend_inline_hash_func(const char *arKey, uint nKeyLength)
{
register ulong hash = 5381 ;
/* variant with the hash unrolled eight times */
for (; nKeyLength >= 8; nKeyLength -= 8) { ​ ​ ​ ​ ​ ​ ​ ​ ​ //Why is this step=8 method?
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++; *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << ; 5) + hash) + *arKey++;
}
switch (nKeyLength) {
case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */                                          Here is the hash of the remaining characters
case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 5: hash = ((hash << ; 5) + hash) + *arKey++; /* fallthrough... */
case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 2: hash = ((hash << 5) + hash) + *arKey++; / *Fallthrough ... */
case 1: Hash = ((Hash & LT; & LT; 5) + Hash) + *ArKey ++; Break;
Case 0: Break; } RReturn hash; // Return hash value
}


ps: There are still two things unclear about the following functions:
The reason for setting hash = 5381?
Is this step=8 loop method for efficiency?

The above introduces the array implemented by hash in huaidanshizenyanglianchengde PHP, including the content of huaidanshizenyanglianchengde. I hope it will be helpful to friends who are interested in PHP tutorials.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template