Skip to content

Commit 6f901b8

Browse files
improve performance and memory usage in HashUtils.djb2 (#376)
#28 """ Runtime profiling indicates this method generates several many memory allocations. Comparing to the JS implementation, we saw the intent of the `hash &= hash` line was to force the JS runtime to keep the number as a 32-bit integer. This is indeed the correct way to do it in JS, but not in Ruby; as a result, the `hash` local will grow ever larger, requiring more and more memory since Ruby supports unbounded integers. Fix: truncate the hash value on each iteration with the same 32-bit `0xFFFFFFF` constant used at the end instead. """ Co-authored-by: Sam Kimbrel <[email protected]>
1 parent 699b704 commit 6f901b8

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

lib/hash_utils.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def self.djb2(input_str)
99
hash = 0
1010
input_str.each_char.each do |c|
1111
hash = (hash << 5) - hash + c.ord
12-
hash &= hash
12+
hash &= 0xFFFFFFFF
1313
end
1414
hash &= 0xFFFFFFFF # Convert to unsigned 32-bit integer
1515
return hash.to_s

0 commit comments

Comments
 (0)