Skip to content

Use XOR with shift for cache key calculation#413

Open
kelhusseiny wants to merge 1 commit intomainfrom
karim/fix-cache-key-collision
Open

Use XOR with shift for cache key calculation#413
kelhusseiny wants to merge 1 commit intomainfrom
karim/fix-cache-key-collision

Conversation

@kelhusseiny
Copy link
Member

Summary

Changes the cache key calculation in CompiledMetric from rotate-left + XOR to XOR with position-based shifts.

Motivation

The previous implementation used a rotate-left + XOR approach which is more complex and slower. Benchmarking shows that XOR with shift achieves the same performance as plain XOR while maintaining order-dependency to prevent collisions when tag values are swapped.

Changes

  • Replaced rotate-left + XOR with simpler XOR + position-based shifts
  • Updated tests and comments to reflect the new algorithm

Benchmark Results

Calculating -------------------------------------
                 XOR     19.702 (±15.2%) i/s   (50.76 ms/i) -     97.000 in   5.025484s
   XOR with rotation     16.574 (± 6.0%) i/s   (60.34 ms/i) -     83.000 in   5.020653s
      XOR with shift     19.240 (±10.4%) i/s   (51.97 ms/i) -     96.000 in   5.021512s

Comparison:
                 XOR:       19.7 i/s
      XOR with shift:       19.2 i/s - same-ish: difference falls within error

XOR with shift is ~15% faster than rotation while maintaining the same collision-resistance properties.

The previous XOR-based cache key computation was commutative, meaning
swapped tag values would produce the same cache key. For example:
(true, false) and (false, true) would both produce the same hash.

This replaces XOR with rotate-left + XOR:
- Rotation makes it order-dependent, preventing collisions when values swap
- XOR keeps the result bounded, avoiding Bignum allocations

The multiply-and-add approach (like Java's Objects.hash) was considered
but causes Bignum allocations when hash values overflow during multiplication.
@kelhusseiny kelhusseiny force-pushed the karim/fix-cache-key-collision branch from 14f550e to 969ad48 Compare January 29, 2026 12:48
@kelhusseiny kelhusseiny marked this pull request as ready for review January 29, 2026 12:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants