惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Privacy International News Feed
Martin Fowler
Martin Fowler
D
Docker
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
U
Unit 42
T
Tailwind CSS Blog
J
Java Code Geeks
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
F
Fortinet All Blogs
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
L
LINUX DO - 最新话题
Microsoft Security Blog
Microsoft Security Blog
N
News and Events Feed by Topic
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
NISL@THU
NISL@THU
小众软件
小众软件
博客园 - 聂微东
博客园 - Franky
有赞技术团队
有赞技术团队
P
Palo Alto Networks Blog
爱范儿
爱范儿
H
Hacker News: Front Page
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cisco Blogs
P
Proofpoint News Feed
I
InfoQ
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
H
Heimdal Security Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python Memory Optimization: How CPython's Memory Pool Works
James Lee · 2026-05-17 · via DEV Community

Python's Memory Management Architecture

As we all know, computer hardware resources are managed by the operating system — memory is no exception. Applications request memory from the OS via system calls, and C library functions wrap those system calls into a general-purpose memory allocator, exposing the familiar malloc family of functions.

This general-purpose allocator implemented by the C library is an important dividing line — it sits at Layer 0 of the memory management hierarchy. Everything above it is application-level memory management; everything below it is the OS internals hidden beneath the surface.

┌─────────────────────────────────────────────┐
│  Layer 3: Object-specific allocators        │  e.g. float free-list cache
├─────────────────────────────────────────────┤
│  Layer 2: Unified object allocator          │  object.tp_alloc / PyObject_New
│           (PyMem_XXXX interface)            │
├─────────────────────────────────────────────┤  ← Python's own memory mgmt
│  Layer 1: Python Memory Pool (pymalloc)     │  ★ The focus of this article
│           handles allocations ≤ 512 bytes   │
├─────────────────────────────────────────────┤
│  Layer 0: C Library (glibc / malloc)        │  General-purpose allocator
├─────────────────────────────────────────────┤
│  Layer -1: OS Virtual Memory Manager        │  Page-table based, MMU involved
├─────────────────────────────────────────────┤
│  Layer -2: Physical Memory + Disk (swap)    │  Hardware level
└─────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

The green zone (Layers 1–3) is Python's own memory management, consisting of 3 layers:

  • Layer 1: A memory allocator that intercepts all memory requests. Its core is the memory pool — the star of this article.
  • Layer 2: Built on top of the unified PyMem_XXXX interface from Layer 1, implements unified object memory allocation (object.tp_alloc).
  • Layer 3: Serves specific object types, such as the float free-object cache pool introduced in earlier chapters.

Why Doesn't Python Just Use malloc Directly?

There are several reasons CPython builds its own layer on top of malloc:

  1. Introducing a memory pool absorbs the pressure from frequent object creation and destruction.
  2. It minimizes memory fragmentation and improves memory utilization efficiency.
  3. There are many malloc implementations, and their performance varies wildly across platforms.

The Challenge of Memory Fragmentation

Memory fragmentation is a major headache for classic memory allocators, and its consequences can be severe. Here's a typical example:

Total free memory: 1900K
┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐
│ used │ 100K │ used │ 200K │ used │1600K │ used │
│      │ free │      │ free │      │ free │      │
└──────┴──────┴──────┴──────┴──────┴──────┴──────┘

Request: 1000K contiguous → ❌ FAIL
(1900K free in total, but no single contiguous block ≥ 1000K)

Enter fullscreen mode Exit fullscreen mode

Even though there's still 1900K of free memory, it's scattered across a series of non-contiguous fragments — making it impossible to allocate even 1000K.

Root Cause Analysis

To solve the problem, we must first understand what causes it.

Applications request memory blocks of unpredictable sizes — some large, some small. The timing of frees is equally unpredictable. Classic allocators manage all sizes together and allocate in arrival order:

Step 1: Initial state — memory is contiguous

[ A | B | C | D | E |      free      ]

Enter fullscreen mode Exit fullscreen mode

Step 2: Large blocks can be split and re-allocated

[ A | b1| b2| C | D | E |   free     ]
      ↑ B was split into b1, b2

Enter fullscreen mode Exit fullscreen mode

Step 3: Earlier allocations are not necessarily freed first — holes appear

[ A |hole| b2| C |hole| E |  free    ]
       ↑ b1 freed    ↑ D freed

Enter fullscreen mode Exit fullscreen mode

Step 4: Over time, fragmentation worsens

[hole|hole| b2|hole|hole| E |hole    ]

Enter fullscreen mode Exit fullscreen mode

The root cause is clear: mixing different-sized allocations in the same memory region, then splitting large blocks for re-allocation, creates gaps that are too small and scattered to reuse.


Solution: Size-Segregated Memory Management

Once we've identified the root cause, the solution becomes obvious — divide memory into separate regions by block size, and manage each independently.

A simple example:

┌─────────────────┬─────────────────┬─────────────────┐
│   Small Region  │  Medium Region  │   Large Region  │
│   (e.g. ≤64B)   │  (65B – 256B)   │  (257B – 512B)  │
├────────┬────────┼────────┬────────┼────────┬────────┤
│ page 1 │ page 2 │ page 1 │ page 2 │ page 1 │ page 2 │
│[8B blk]│[8B blk]│[128B ] │[128B ] │[256B ] │[256B ] │
└────────┴────────┴────────┴────────┴────────┴────────┘

Enter fullscreen mode Exit fullscreen mode

As shown, memory is divided into small, medium, and large regions. Each region consists of several memory pages, and each page is divided into uniform-sized blocks.

This way, small block allocations cannot fragment the large-block region.

Fragmentation within each region still exists, but those fragments are always reusable by the next same-size request. Furthermore, with an optimized allocation strategy, fragmentation can be further reduced. For example, new allocations are made from page 1 first — page 2 gradually empties out and can eventually be reclaimed entirely.

Inside the Python VM, objects are constantly being created and destroyed, triggering frequent memory requests and releases. These allocations are generally small but happen at very high frequency. Python specifically designed the memory pool to optimize this scenario.

The 512-Byte Threshold

Request size     →  Allocator used
─────────────────────────────────────────
0 bytes          →  malloc() directly
1 – 512 bytes    →  pymalloc memory pool  ✅
> 512 bytes      →  malloc() directly

Enter fullscreen mode Exit fullscreen mode

Why Not One Pool Per Byte Size?

Python does not create a separate pool for every possible size (1–512). Reasons:

  • 512 pool types would add enormous complexity.
  • More pool types = more overhead.
  • If a specific size is only requested once, the rest of that page's blocks are wasted.

Instead, Python uses 8-byte granularity, rounding up to the nearest multiple of 8. This gives 64 size classes:

Request Size Block Size Allocated Class Index
1 – 8 8 0
9 – 16 16 1
17 – 24 24 2
25 – 32 32 3
497–504 504 62
505–512 512 63

Memory Utilization

This approach sacrifices some memory utilization. For the 8-byte class, average utilization is (1+8)/2/8 ≈ 56.25%. However, averaged across all 64 size classes, utilization is actually quite high:

total_requested = 0
total_allocated = 0

for i in range(1, 513):
    total_requested += i
    total_allocated += (i + 7) // 8 * 8

print('{:.2f}%'.format(total_requested / total_allocated * 100))
# 98.65%

Enter fullscreen mode Exit fullscreen mode

Overall memory utilization reaches 98.65% — excellent.


Memory Pool Implementation

pool — The Core Data Structure

Now let's look at the source code in Objects/obmalloc.c.

Note: On 64-bit systems, CPython actually uses 16-byte alignment (not 8-byte). For clarity, we'll use 8-byte in our diagrams (these macros are configurable anyway).

#if SIZEOF_VOID_P > 4
#define ALIGNMENT              16    /* must be 2^N */
#define ALIGNMENT_SHIFT         4
#else
#define ALIGNMENT               8    /* must be 2^N */
#define ALIGNMENT_SHIFT         3
#endif

Enter fullscreen mode Exit fullscreen mode

A helper macro converts a class index to block size (e.g., class 1 → 16 bytes):

#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)

Enter fullscreen mode Exit fullscreen mode

Each memory page (pool) is 4KB:

#define SYSTEM_PAGE_SIZE   (4 * 1024)
#define POOL_SIZE          SYSTEM_PAGE_SIZE   // 4096 bytes

Enter fullscreen mode Exit fullscreen mode

Python treats each memory page as a pool — a container of uniform-sized blocks. At the start of each page sits a pool_header struct:

struct pool_header {
    union { block *_padding;
            uint count; } ref;      /* number of allocated blocks   */
    block *freeblock;               /* pool's free list head        */
    struct pool_header *nextpool;   /* next pool of this size class */
    struct pool_header *prevpool;   /* previous pool of this class  */
    uint arenaindex;                /* index into arenas            */
    uint szidx;                     /* block size class index       */
    uint nextoffset;                /* offset to next virgin block  */
    uint maxnextoffset;             /* largest valid nextoffset     */
};

Enter fullscreen mode Exit fullscreen mode

Key fields:

  • count — number of allocated blocks
  • freeblock — pointer to the head of the free block linked list
  • nextpool / prevpool — doubly-linked list pointers
  • szidx — size class index
  • nextoffset — offset to the next uninitialized block
  • maxnextoffset — maximum valid block offset

Pool Initialization and Block Allocation

When a new 4KB page is initialized, the first block is immediately allocated (since initialization is always triggered by an allocation request):

┌──────────────┬───────────────────────────────────────┐
│ pool_header  │ [blk0:alloc'd] [blk1] [blk2] [blk3]… │
│  (64 bytes)  │  ↑ already given out                  │
└──────────────┴───────────────────────────────────────┘
                 nextoffset points here ──────────────→

Enter fullscreen mode Exit fullscreen mode

As more allocations come in, blocks are taken from the uninitialized (grey) area:

┌──────────────┬──────────────────────────────────────┐
│ pool_header  │ [alloc][alloc][alloc][blk3][blk4]…   │
└──────────────┴──────────────────────────────────────┘
                                  ↑ nextoffset

Enter fullscreen mode Exit fullscreen mode

When a block is freed (e.g., block 0), Python inserts it at the head of the free list. Each free block stores a next pointer in its first bytes, pointing to the next free block:

freeblock
    │
    ▼
┌───────┐     ┌───────┐
│ blk0  │────▶│ blk2  │────▶ NULL
│(freed)│     │(freed)│
└───────┘     └───────┘

Enter fullscreen mode Exit fullscreen mode

Pool States

A pool can be in one of three states:

┌─────────────────────────────────────────────────────────┐
│  empty  │  All blocks free. count=0. Can be reclaimed   │
│         │  or reused for a different size class.        │
├─────────────────────────────────────────────────────────┤
│  used   │  Some blocks allocated, some free.            │
│         │  Actively serves allocation requests.         │
├─────────────────────────────────────────────────────────┤
│  full   │  All blocks allocated. freeblock=NULL.        │
│         │  Python ignores it until a block is freed.    │
└─────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

Why do states matter? They determine Python's handling strategy:

  • empty: The page can be returned to the OS or cached for reuse.
  • full: Python sets it aside and ignores it.
  • used: Python organizes these into a doubly-linked circular list for active allocation.

The usedpools Array

Used Pool Linked List

used pools of the same size class are linked together via nextpool / prevpool into a doubly-linked circular list:

dummy node (virtual head)
     │
     ▼
┌─────────┐    ┌─────────┐    ┌─────────┐
│ pool_A  │◀──▶│ pool_B  │◀──▶│ pool_C  │
│ 16B cls │    │ 16B cls │    │ 16B cls │
│ (full-ish)   │ (half)  │    │ (almost │
│         │    │         │    │  empty) │
└─────────┘    └─────────┘    └─────────┘

Enter fullscreen mode Exit fullscreen mode

An empty list has pool->nextpool == pool (points to itself).

Python always allocates from the first pool in the list. When a pool becomes full, it's removed from the list. When a freed block causes a full pool to become used again, it's re-inserted at the head — ensuring the fullest pools stay at the front, and the emptiest pools drift to the tail and eventually become empty.

After free: full → used, re-insert at head
┌──────────┐    ┌─────────┐    ┌──────────────┐
│ pool_new │◀──▶│ pool_A  │◀──▶│ pool_B(empty)│
│(re-added)│    │         │    │  → reclaimed │
└──────────┘    └─────────┘    └──────────────┘

Enter fullscreen mode Exit fullscreen mode

Pool List Array (usedpools)

Python maintains one used-pool list per size class (64 total). Naively, this would require 64 full pool_header dummy nodes:

64 × 48 bytes = 3072 bytes ≈ 3KB

Enter fullscreen mode Exit fullscreen mode

But Python's authors are more frugal. Since dummy nodes only use nextpool and prevpool, they pack them into a flat pointer array called usedpools — each dummy node becomes just 2 pointers:

usedpools array (128 pointers = 1KB):

index:  [0]  [1]  [2]  [3]  [4]  [5]  [6]  [7] ...
        ├─────────┤  ├─────────┤  ├─────────┤
        │ class 0 │  │ class 1 │  │ class 2 │  ...
        │ (8B)    │  │ (16B)   │  │ (24B)   │
        └─────────┘  └─────────┘  └─────────┘

Enter fullscreen mode Exit fullscreen mode

The trick: treat the address of usedpools[i] as if it were a pool_header*. Since only nextpool and prevpool are ever accessed on dummy nodes, the out-of-bounds access to other fields never actually happens.

Result: 64 × 16 bytes = 1024 bytes = 1KB — saving two-thirds of the memory compared to the naive approach.