memory
Grow-able byte buffers, string interning pools, and read-only access to allocator and garbage-collector statistics. Import it with import memory.
Buffers and pools are referenced by integer handles returned from their new functions; free them with free when done.
memory.buffer
| Function | Signature | Description |
|---|
new | memory.buffer.new() → int | Allocate a new buffer; returns its handle |
write | memory.buffer.write(id: int, data: string) → bool | Append data to the buffer |
read | memory.buffer.read(id: int) → string | Read the full buffer contents |
reset | memory.buffer.reset(id: int) → void | Empty the buffer, keeping it allocated |
len | memory.buffer.len(id: int) → int | Current byte length |
free | memory.buffer.free(id: int) → void | Release the buffer |
memory.pool
A pool deduplicates equal strings (interning).
| Function | Signature | Description |
|---|
new | memory.pool.new() → int | Allocate a new interning pool; returns its handle |
intern | memory.pool.intern(id: int, s: string) → string | Return the pooled copy of s, adding it if new |
has | memory.pool.has(id: int, s: string) → bool | Whether s is already interned |
size | memory.pool.size(id: int) → int | Number of interned strings |
free | memory.pool.free(id: int) → void | Release the pool |
memory.alloc
| Function | Signature | Description |
|---|
stats | memory.alloc.stats() → string | JSON string with alloc, totalAlloc, sys, numGC, goroutines |
heapAlloc | memory.alloc.heapAlloc() → int | Bytes of allocated heap objects |
heapSys | memory.alloc.heapSys() → int | Bytes of heap memory obtained from the OS |
numGC | memory.alloc.numGC() → int | Completed GC cycles |
memory.gc
| Function | Signature | Description |
|---|
run | memory.gc.run() → void | Run a garbage collection now |
setPercent | memory.gc.setPercent(pct: int) → int | Set the GC target percentage; returns the previous value |
freeOSMemory | memory.gc.freeOSMemory() → void | Force a GC and return unused memory to the OS |
Example
import memory
// build a string with a buffer
let buf = memory.buffer.new()
memory.buffer.write(buf, "hello ")
memory.buffer.write(buf, "world")
print(memory.buffer.read(buf)) // hello world
print(memory.buffer.len(buf)) // 11
memory.buffer.free(buf)
// intern repeated strings
let pool = memory.pool.new()
let a = memory.pool.intern(pool, "tag")
let b = memory.pool.intern(pool, "tag")
print(memory.pool.size(pool)) // 1
memory.pool.free(pool)
// inspect heap usage
print(memory.alloc.heapAlloc())