Back to feed
Dev.to
Dev.to
7/7/2026
The original title is: "AI Wrote a Thread-Safe Counter. The CPU Made It 5x Slower."

The original title is: "AI Wrote a Thread-Safe Counter. The CPU Made It 5x Slower."

Original: AI Wrote a Thread-Safe Counter. The CPU Made It 5x Slower.

Short summary

An AI assistant wrote correct but slow multithreaded counter code; measurements on Apple Silicon revealed a 5x performance penalty caused by false sharing—multiple threads contending for the same CPU cache line despite updating different array elements. Padding each counter to occupy its own 128-byte cache line recovers the lost parallelism. The technique applies broadly to production code: sharded counters, cache statistics, and LRU metadata often silently suffer the same contention.

  • AI wrote correct code but 5x slower due to false sharing (multiple threads contending for same cache line)
  • Solution: pad each counter to 128 bytes so each occupies its own cache line
  • Pattern appears in production systems: sharded counters, cache statistics, LRU metadata

Generated with AI, which can make mistakes.

Is this a good recommendation for you?

Comments

Failed to load comments. Please try again.

Explore more