search
HomeBackend DevelopmentPHP TutorialPHP string hash function algorithm implementation code

  1. function DJBHash($str) // 0.22
  2. {
  3. $hash = 0;
  4. $n = strlen($str);
  5. for ($i = 0; $i {
  6. $hash += ($hash }
  7. return $hash % 701819;
  8. }
  9. function ELFHash($str) // 0.35
  10. {
  11. $hash = $x = 0;
  12. $n = strlen($str);
  13. for ($i = 0; $i {
  14. $hash = ($hash if(($x = $hash & 0xf0000000) != 0)
  15. {
  16. $hash ^= ($x>> 24);
  17. $hash &= ~$x;
  18. }
  19. }
  20. return $hash % 701819;
  21. }
  22. function JSHash($str) // 0.23
  23. {
  24. $hash = 0;
  25. $n = strlen($str);
  26. for ($i = 0; $i {
  27. $hash ^= (($hash > 2));
  28. }
  29. return $hash % 701819;
  30. }
  31. function SDBMHash($str) // 0.23
  32. {
  33. $hash = 0 ;
  34. $n = strlen($str);
  35. for ($i = 0; $i {
  36. $hash = ord($str[$i]) + ($hash }
  37. return $hash % 701819;
  38. }
  39. function APHash($str) // 0.30
  40. {
  41. $hash = 0 ;
  42. $n = strlen($str);
  43. for ($i = 0; $i {
  44. if (($i & 1 ) == 0 )
  45. {
  46. $hash ^= (($hash > 3 ));
  47. }
  48. else
  49. {
  50. $hash ^= ( ~ (($hash > 5)));
  51. }
  52. }
  53. return $hash % 701819;
  54. }
  55. function DEKHash($str) // 0.23
  56. {
  57. $n = strlen($str);
  58. $hash = $n;
  59. for ($i = 0; $i {
  60. $hash = (($hash > 27)) ^ ord($str[$i]);
  61. }
  62. return $hash % 701819;
  63. }
  64. function FNVHash($str) // 0.31
  65. {
  66. $hash = 0;
  67. $n = strlen($str);
  68. for ($i = 0; $i {
  69. $hash *= 0x811C9DC5;
  70. $hash ^= ord($str[$i]);
  71. }
  72. return $hash % 701819;
  73. }
  74. function PJWHash($str) // 0.33
  75. {
  76. $hash = $test = 0;
  77. $n = strlen($str);
  78. for ($i = 0; $i {
  79. $hash = ($hash
  80. if(($test = $hash & -268435456) != 0)
  81. {
  82. $hash = (( $hash ^ ($test>> 24)) & (~-268435456));
  83. }
  84. }
  85. return $hash % 701819;
  86. }
  87. function PHPHash($str) // 0.34
  88. {
  89. $hash = 0;
  90. $n = strlen($str);
  91. for ($i = 0; $i {
  92. $hash = ($hash if (($g = ($hash & 0xF0000000)))
  93. {
  94. $hash = $hash ^ ($g>> 24);
  95. $hash = $hash ^ $g;
  96. }
  97. }
  98. return $hash % 701819;
  99. }
  100. function OpenSSLHash($str) // 0.22
  101. {
  102. $hash = 0;
  103. $n = strlen($str);
  104. for ($i = 0; $i {
  105. $hash ^= (ord($str[$i]) }
  106. return $hash % 701819;
  107. }
  108. function MD5Hash($str) // 0.050
  109. {
  110. $hash = md5($str);
  111. $hash = $hash[0] | ($hash[1] return $hash % 701819;
  112. }
复制代码

Algorithm description: The comment behind the function is the execution speed (unit: s) of 1000 times in my local test. It can be seen that MD5Hash is the fastest, and it is much faster than other functions... But it can also be seen from the algorithm of this function. , it only relies on the first 7 characters of the string after md5. That is to say, if the first 7 characters are the same, the hash value obtained is exactly the same, so in fact, its distribution is not very trustworthy. ....If calculated based on 32 characters, the speed will be far slower than other algorithms...

Except for MD5Hash, other algorithms will be affected by the length of the string. The longer it is, the slower it is. I used 10 characters in English for the test. The final return of each function $hash % 701819; 701819 represents the maximum capacity of the hash, which means that the final number range obtained by these hash functions is 0~701819. This number can be changed. It is generally considered to use a large one. The distribution of prime number results will be relatively even. Several suggested values ​​near 701819 are: 175447, 350899, 1403641, 2807303, 5614657.

What can this be used for...

Why do we need to organize and test these hash algorithms? I am writing a multi-user blog. Well... I also mentioned it in the previous blog. Multi-user blogs generally have a function, which is to use a user name that is a combination of English and numbers. as the blog address (second-level domain name or directory). Then there is a question, how to get the user's ID based on the user name, is there one more query? With the hash function, there is no need. Use the hash function to process the user name, get a number, and then do certain processing on the number (I divided it into hierarchical directories based on 2 digits. The purpose is to prevent too many files in one directory. file (which affects the disk retrieval speed), and then a path is formed, and the corresponding ID is saved in the file under this path (I personally recommend the user name as the file name), so that the user's ID can be obtained directly based on the user name. , no query is required, the user name is used as the file name, so even if the final results are the same, they are in different files, so there is no need to worry about collisions.

Of course...if your system operates entirely based on user names, then I didn't say this before = =b, I quietly criticize SELECT because numbers are faster than strings.

I chose the DJB algorithm. If the MD5 distribution test is acceptable after it goes online, I will consider switching to it.

It can also be seen from here that hashing is actually very useful for distribution. Haha, it can be used for caching, static or other things that require distributed storage.



Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.