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?