Part V — The Modern Experience Layer · Chapter 33 · Lesson 2 of 2
Caches, connection pools, profiling and fast hashing
The performance helpers live in pealang/performance.py and are registered directly in the built-in analysis namespace. No import is needed; PeaLang's import takes a quoted path to another .pea file, not a Python module name. The names below are the 3.1.39 surface.
mmap I/O
let path = analysis.mmap_write("data.bin", "record one record two")
let head = analysis.mmap_read(path, 0, 4096)
let pattern = interop.call_python("builtins", "bytes", "record two", "utf-8")
let offsets = analysis.mmap_search(path, pattern)
mmap_write(path, data, offset=0) writes bytes (a string is UTF-8 encoded) and returns the path. mmap_read(path, offset=0, size=None) returns decoded text, not bytes; omit size to read to the end of the file. mmap_search(path, pattern) takes a bytes pattern and returns every integer offset where it occurs. PeaLang has no byte literal, so the example builds one through the built-in interop namespace. Memory mapping avoids the copy-then-parse dance for large files, but the mapping reflects the file as it exists now; if the file can be replaced mid-run, checksum first.
AdvancedCache — four policies, one API
let lru = analysis.AdvancedCache(500, analysis.CachePolicy.LRU)
let fifo = analysis.AdvancedCache(500, analysis.CachePolicy.FIFO)
let ttl = analysis.AdvancedCache(500, analysis.CachePolicy.TTL, 300)
lru.put("user:42", record)
let hit = lru.get("user:42")
print lru.stats()
The class is AdvancedCache(capacity=128, policy="lru", ttl=None) with CachePolicy.LRU/LFU/FIFO/TTL constants and get, put, clear and stats methods. stats() returns size, capacity, policy, hits, misses and hit rate. Policy selection should come from measured eviction behavior, not habit:
- LRU / LFU — in 3.1.39 both use the same lowest-access-count eviction path. Do not assume recency and frequency are implemented differently; read the source before relying on the distinction.
- FIFO — evicts the earliest inserted key. Predictable, blind to value, and cheap.
- TTL — adds expiry to whichever policy is selected; entries are dropped on
getonce their deadline passes. Correctness, not raw speed.
There are no LRUCache, LFUCache, FIFOCache or TTLCache classes in performance.py. analysis.LRUCache comes from the separate robustness.py module.
Connection pooling
let builtins = interop.import_python("builtins")
let pool = analysis.ConnectionPool(builtins.dict, 10, 30.0)
let conn = pool.acquire()
pool.release(conn)
print pool.stats()
The signature is ConnectionPool(factory, max_size=10, timeout=30.0); factory must be a Python callable invoked with no arguments. Methods are acquire(), release(conn), close_all() and stats(). Pooling bounds how many connections are created; exhaustion raises RuntimeError. The timeout argument is stored on the object but does not make acquire() wait, so pair the pool with the per-call limits from Chapter 14.
Profiling without guessing
let timed = analysis.profile_function(analysis.fast_hash, {"user": 42, "role": "admin"})
print timed.elapsed_ms
print timed.result
profile_function(func, *args, **kwargs) times one call and returns {"result": ..., "elapsed_ms": ...}. It expects a Python callable; PeaLang-defined functions are not Python callables unless the host helper explicitly bridges them (as analysis.filter_rows and analysis.add_column do). analysis.Profiler also exists for Python hosts: time(name) is a context manager and summary() reports count, total, mean, min and max in milliseconds. Run measurements on the real workload; synthetic microbenchmarks lie politely.
Batching and parallel chunks
let bs = analysis.optimize_batch_size(total_items, 1.5, 10.0)
let chunks = analysis.parallel_chunks(records, 8)
optimize_batch_size(total_items, item_cost_ms=1.0, overhead_ms=10.0) is a small heuristic: sqrt(overhead_ms / item_cost_ms), capped at total_items. parallel_chunks(items, num_chunks=4) slices a list using len(items) // num_chunks, so an uneven division can produce more than num_chunks chunks. Both are starting points for measurement, not guarantees about tail latency.
fast_hash
let h = analysis.fast_hash({"user": 42, "role": "admin"})
fast_hash serializes the value with sorted keys and returns a SHA-256 hex digest. Small, stable content hashes are useful for cache keys, deduping and content-addressable storage. Do not use it for passwords — use a slow KDF — and do not treat it as authenticated integrity evidence.
Guided practice
- Replace one full-file read of a >100 MB file with
analysis.mmap_read; measure end-to-end including parse time, not just the read. - Pick FIFO vs TTL for your cache using a recorded access log; keep the eviction histogram and note that LRU/LFU share a path in this release.
- Time
analysis.fast_hashwithanalysis.profile_functionover a realistic payload and archive the baseline. - Use
analysis.optimize_batch_sizeon one batched job and compare latency at old and new sizes.