Reference library

Concurrency & performance

asyncio, threading, multiprocessing, and profiling-friendly performance patterns.

6 matches
Concurrency & performance medium

How to Reduce Instance Memory with __slots__ in Python

Demonstrates that classes with __slots__ use less memory per instance than regular classes because they skip the instance __dict__.

__slots__ memory performance
Python
class SlottedPoint:
    __slots__ = ('x', 'y', 'z')

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


class RegularPoint:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


if __name__ == "__main__":
    regular = RegularPoint(1, 2, 3)…
11 0 Open
Concurrency & performance medium

How to Share Memory Between Processes in Python with multiprocessing.Value and Array

Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.

multiprocessing shared-memory concurrency
Python
import multiprocessing

def worker(shared_value, shared_array, index):
    shared_value.value += 10
    shared_array[index] = shared_array[index] * 2

if __name__ == "__main__":
    shared_value = multiprocessing.Value("i", 5)
    shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])

    processes = []
    for i…
13 0 Open
Concurrency & performance easy

How to Use Array Typecodes for Compact Numeric Storage in Python

This code demonstrates how to use the `array` module with typecodes to store integers, floats, and bytes in a memory-efficient way compared to standard Python lists.

array memory performance
Python
from array import array

def demonstrate_array_types():
    # Compact integer arrays
    small_ints = array('i', [1, 2, 3, 4, 5])
    unsigned_ints = array('I', [10, 20, 30])
    
    # Floating point arrays
    floats = array('f', [1.5, 2.5, 3.5])
    doubles = array('d', [1.123456789, 2.987654321])
    
    # Charac…
15 0 Open
Concurrency & performance medium

How to Use a Weakref Cache to Avoid Memory Leaks in Python

This code demonstrates building a value cache with weakref.WeakValueDictionary so objects can be garbage collected when no longer referenced, preventing memory leaks.

weakref caching memory
Python
import weakref
import gc


class ExpensiveObject:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"ExpensiveObject('{self.name}')"


class ObjectCache:
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()

    def get_or_create(self, name):
       …
13 0 Open
Concurrency & performance medium

Profile Memory Usage with tracemalloc Snapshot Diff in Python

Use tracemalloc to take two memory snapshots, compute a diff, and print the top changes (size and count) by line number.

tracemalloc memory-profile performance
Python
import tracemalloc

def profile_memory():
    tracemalloc.start()
    
    # Allocate some objects to track
    data = [i * 2 for i in range(10000)]
    text = "x" * 5000
    nested = {"key": [1, 2, 3], "value": (4, 5)}
    
    # Take first snapshot
    snapshot1 = tracemalloc.take_snapshot()
    
    # Free some mem…
11 0 Open
Concurrency & performance easy

Using a Python Generator Instead of a List to Save Memory

Compare a list approach with a generator to stream values lazily, avoiding memory-heavy storage of large sequences.

generator lazy-evaluation memory
Python
def fibonacci_generator(limit):
    a, b = 0, 1
    count = 0
    while count < limit:
        yield a
        a, b = b, a + b
        count += 1


def sum_first_n(generator, n):
    total = 0
    for i, value in enumerate(generator):
        if i >= n:
            break
        total += value
    return total


if __…
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Concurrency & performance — Python code examples

What you will find here

This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.