Python Tuples vs Lists: Performance Optimization

Why creating a tuple is faster than creating a list in Python? TL;DR: Python doesn’t always create new objects, it uses cached ones! Creating an object is expensive, it needs to ask the OS for memory. To avoid this, CPython implementation uses FREE LISTS for immutable objects like Tuples. How does it work? 1. When you stop using a small tuple (up to 20 elements), Python doesn't delete it from RAM. 2. It moves it to a "Free List" (a specialised cache). 3. When you need a new tuple of that same size, Python just grabs an old one from the cache and renews it. Lists, however, are rarely recycled this way because of their dynamic nature makes them too complex to keep in a simple cache. Why this matters? -> In a a real-time game engine, or a data processing pipeline, you might be creating objects millions of times per second. -> The List Tax: Every time you use [a, b], you are potentially triggering a memory allocation request. -> The Tuple Win: Every time you use (a, b), you are likely just grabbing a "pre-warmed" slot from Python’s internal cache. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment

  • text

To view or add a comment, sign in

Explore content categories