🔍 Object vs Array Lookup in JavaScript — Performance and Hash Table Insight
đź§ Introduction
You often need to count character frequencies when building algorithms like anagram checks. There are two common ways to store this frequency data in JavaScript:
- ✅ Object →
{ 'a': 2, 'b': 1, ... }
- ✅ Array →
[1, 0, 2, 0, ...]
(26 elements for lowercase letters)
But which is faster? Why? And how do hash tables come into play?
Link for Understanding Hash Table: https://youtu.be/FsfRsGFHuv4?si=Cmx7byUund0PHJpT
⚙️ Understanding Hash Tables
A hash table is a data structure that maps keys to values. JavaScript objects are built on top of hash tables.
📦 How Objects Work:
When you do something like:
let obj = {};
obj['a'] = 1;
Under the hood:
- JavaScript hashes the key
'a'
to a specific memory location. - Stores the value
1
at that location. - Lookup (
obj['a']
) uses the same hash function to quickly retrieve the value.
⏱️ This gives average O(1) lookup time, but:
- In rare cases, there can be collisions, re-hashing, or performance hits due to memory handling and dynamic growth.
- JavaScript engines add some overhead to manage these objects.
🔢 Arrays — Not Hash Tables
JavaScript arrays are more like indexed lists. Accessing an element at a given index is a direct memory access (e.g., arr[0]
), which is usually faster than hash-based lookup.
In this optimized anagram check:
const count = new Array(26).fill(0);
count[s.charCodeAt(i) - 97]++;
We map 'a'
to index 0
, 'b'
to 1
, ..., 'z'
to 25
, by subtracting 97
(ASCII code of 'a'
).
âś… Arrays are ideal for fixed ranges like lowercase letters.
🥊 Object vs Array: Performance Comparison
đź§Ş In practice, arrays outperform objects when:
- You know the range (like lowercase letters).
- You’re doing many lookups and updates in a loop.
📌 Summary
- Objects use hash tables, which are great for dynamic and flexible keys.
- Arrays use direct indexing, which is faster and more memory-efficient for fixed character ranges.
- For problems like checking anagrams, arrays are a better choice when the input is constrained (e.g., lowercase letters only).
I hope this helps you to understand :)
Please do follow me on Medium for more such content.