본문으로 건너뛰기
개발 뉴스로
기타dev.to··원문 약 4

3ms에서 0ms까지: C++ 맵의 숨겨진 메모리 함정

From 3ms to 0ms: The Hidden Memory Trap in C++ Maps

3ms에서 0ms까지: C++ 맵의 숨겨진 메모리 함정 나는 내 인생에서 가장 깔끔한 한 줄짜리 글을 쓰고 있다고 생각했습니다.

핵심 요약

자동 요약
  1. 13ms에서 0ms까지: C++ 맵의 숨겨진 메모리 함정 나는 내 인생에서 가장 깔끔한 한 줄짜리 글을 쓰고 있다고 생각했습니다.
  2. 2Two Sum을 해결하기 위해 1부터 시작하는 인덱스를 unordered_map에 저장하여 if 문 내에서 직접 보완 항목을 확인할 수 있습니다.
  3. 3if (mp[target - nums[i]]) { return {mp[target - nums[i]] - 1, i}; } 통과했습니다.

원문 본문

출처 · dev.to

From 3ms to 0ms: The Hidden Memory Trap in C++ Maps

I thought I was writing the cleanest one-liner of my life.

To solve Two Sum, I stored 1-based indices in an unordered_map so I could check for complements directly inside an if statement:

if (mp[target - nums[i]]) { return {mp[target - nums[i]] - 1, i}; } 

It passed. But it took 3ms.

On a whim, I swapped that single line to mp.find(). The runtime plummeted straight to 0ms.

Why would two operations that look like basic O(1) lookups perform so radically differently?


The Secret Life of `operator[]`

In C++, square brackets aren't just looking through the window. If the key isn't there, C++ assumes you're lonely and creates a new friend for you on the spot.

When you call mp[missing_key]:

  1. It allocates a brand-new node on the heap.
  2. It inserts missing_key with a default value of 0.
  3. It hands back a reference to that 0.

Because 0 evaluates to false, my if condition technically worked. But behind the scenes, every single failed lookup left a ghost entry behind. My map was hoarding junk data, thrashing CPU caches, and triggering expensive hash table rehashes mid-loop.

mp.find(), on the other hand, is strictly read-only. If the key isn't there, it returns mp.end() and walks away without touching heap memory.


The Fix

// The 3ms Trap: Allocates heap memory for ghost entries on every miss if (mp[complement]) { ... } // The 0ms Clean Run: Read-only check, zero allocations auto it = mp.find(complement); if (it != mp.end()) { return {it->second, i}; } 

(Tip: In C++20, if you only care about presence and don't need the value right away, mp.contains(key) gives you the same zero-allocation check with even cleaner syntax).


The Rule of Thumb

Never use [] to ask, "Are you there?"
Square brackets are for modifying data, not window shopping.


Have you ever had an optimization that looked slick on paper but quietly blew up your runtime? Drop your favorite sneaky C++ traps or debugging facepalms in the comments!

For further actions, you may consider blocking this person and/or reporting abuse

이 글은 dev.to 의 원문을 정제해 보여드립니다. 저작권은 원저작자에게 있습니다.

#cpp#programming#performance#computerscience

전체 내용이 궁금하다면

dev.to 원문에서 이어 읽기

원문 보기

비슷한 글

5유사도 추천