Back to JavaScript Performance

Use Set/Map for O(1) Lookups

javascriptsetmapdata-structuresperformance
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

When an application performs frequent membership checks against a collection, relying on standard arrays leads to O(n) time complexity because the runtime must scan the entire list for every lookup. As the size of the array increases, this behavior creates significant performance bottlenecks in loops or data transformation pipelines. By refactoring these collections into Set or Map objects, you shift the lookup complexity to O(1), ensuring the time required to verify an item remains constant regardless of the collection size. This technique is essential for processing large datasets, filtering complex state objects, or managing access control lists. Implementing this pattern replaces linear scanning with hash-based retrieval, which drastically improves execution speed and reduces CPU overhead in high-frequency logic paths across your JavaScript codebase.

When to Use This Skill

  • Checking if a user ID exists within an authorized permissions list
  • Deduplicating large arrays of objects by a specific property
  • Efficiently associating metadata with items during a data join operation
  • Tracking visited nodes in graph traversal algorithms

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • optimize this array lookup
  • speed up this filter operation
  • change this list to a set for performance
  • how to avoid O(n) complexity for item verification
  • make this collection lookup faster

What this skill does

  • Converts linear array searches into hash-based constant time lookups
  • Optimizes filtering operations for large datasets
  • Removes duplicate values automatically during Set initialization
  • Allows mapping unique keys to complex values via Map objects
  • Reduces total execution time in iterative data processing

When not to use it

  • When the collection is very small and the overhead of creating the Set outweighs performance gains
  • When you need to maintain the original insertion order and perform frequent index-based access
  • When memory constraints prevent the creation of additional data structures

Example workflow

  1. Identify a recurring Array.includes or Array.find operation inside a loop
  2. Extract the target array into a standalone variable
  3. Instantiate a new Set using the target array as the constructor argument
  4. Replace the .includes method with the .has method on the new Set
  5. Verify the output remains identical while measuring reduced execution time

Pitfalls & limitations

  • !Set and Map initialization carries a one-time upfront cost that might hurt performance for single-use checks
  • !Primitive types work predictably, but object references in Sets are based on memory address rather than structural content
  • !Excessive memory allocation for extremely large sets can impact garbage collection cycles

FAQ

Why is a Set faster than an Array?
A Set uses a hash table internally, allowing it to jump directly to a value's location. An Array must scan every single element one by one until it finds a match.
Does this work for arrays of objects?
It works, but only if you are checking by reference. If you need to check by object properties, you must map those properties to a string or primitive key first.
Is there a memory trade-off?
Yes, Sets and Maps consume more memory than arrays because they store extra metadata for the hash structure. Only prioritize this for collections large enough to impact performance.

How it compares

While manual array searching scales linearly with data growth, moving to Set-based lookup provides a stable, constant-time performance profile that does not degrade as your data volume expands.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## Use Set/Map for O(1) Lookups

Convert arrays to Set/Map for repeated membership checks.

**Incorrect (O(n) per check):**

const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))


**Correct (O(1) per check):**

const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/js-set-map-lookups/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/vercel-labs/agent-skills/js-set-map-lookups/SKILL.md
  • Cursor: ~/.cursor/skills/vercel-labs/agent-skills/js-set-map-lookups/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-set-map-lookups/SKILL.md

🚀 Install with CLI:
npx skills add vercel-labs/agent-skills

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid javascript performance issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under JavaScript Performance and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.