* Batch-allocate per-record objects; reuse CSV writer field buffer
After batch-arena field allocation, profiling cat over 1M-record CSV showed
the remaining ~5M allocations were almost entirely per-record (one each):
the Mlrmap struct, the RecordAndContext wrapper, the CSV writer's []string,
and the go-csv parser's own buffers.
Address the first three:
- mlrval.RecordArena gains NewRecord(), vending the Mlrmap struct itself from
a per-batch slab (respecting --no-hash-records). Rolled out to every
line-based reader (CSV, CSV-lite, TSV, DKVP, NIDX, PPRINT, XTAB, DKVPX) in
place of NewMlrmapAsRecord.
- The CSV reader batch-allocates RecordAndContext wrappers from a per-batch
slab instead of one heap object per record (comment/output-string entries
still allocate individually, but they are rare).
- RecordWriterCSV reuses a single fieldsBuffer []string across records instead
of allocating one per Write; WriteCSVRecordMaybeColorized consumes it
synchronously and the writer is single-goroutine, so this is safe.
Effect (big.*, 1M records, cat, best of 5):
csv 0.26 -> 0.22
dkvp 0.51 -> 0.45 (Mlrmap slab)
For CSV, cat's allocation-object count drops ~5.0M -> ~2.1M. The remaining
~2M are the go-csv parser's per-record backing string and field slice, which
are intrinsic to parsing and would require a zero-copy/batch-slab parser
rework. A CPU profile of cat now shows it is I/O-bound (syscall ~56%, bufio
read+flush), with allocation/GC down to ~10% -- i.e. further allocation
trimming no longer moves cat's wall-clock. GOGC=off confirms (no change).
Verified: go test ./pkg/... and full regression suite pass; output is
byte-identical across all formats including record-retaining verbs (tac),
hashed and --no-hash-records.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Pool DSL stack frames across records (~8-9% on put)
A StackFrameSet lives on the persistent runtime.State and is reused across
all records, but every block entry (StatementBlockNode.Execute does
PushStackFrame/PopStackFrame, which runs once per record for the main block,
plus once per if/for/etc.) allocated a fresh StackFrame -- a []*var slice and
a map[string]int -- and discarded it on exit. For `put`/`filter` that is
millions of throwaway allocations.
Since push/pop is strictly LIFO, retain popped frames in a per-frameset free
list and clear-and-reuse them on the next push. After the first record
establishes the max block-nesting depth, per-record block execution is
allocation-free for frames. len(stackFrames) remains the logical depth, so
get/set/defineTyped/unset/etc. are unchanged.
Measured (big.csv, 1M rows, best of 4):
put chain-1 0.78 -> 0.72 (~8%)
put chain-4 0.96 -> 0.87 (~9%)
Allocation objects for put chain-1 drop ~23.1M -> ~20.0M (the per-record
newStackFrame churn, ~2.86M, is eliminated). UDF calls still allocate a fresh
frameset per call (PushStackFrameSet); pooling those is a separate change.
The dominant remaining DSL allocator is FromFloat (~6.8M, interior arithmetic
temporaries); eliminating it needs node-owned result slots + in-place bif
variants, a much larger and aliasing-sensitive change, left for follow-up.
Verified: go test ./pkg/... and full regression suite pass; put output is
byte-identical, including UDFs with locals/loops/blocks.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Pool DSL stack-frame *sets* across UDF/subr calls (~31% on function-heavy put)
Companion to the per-block frame pooling: that left PushStackFrameSet /
PopStackFrameSet (entered once per user-defined function or subroutine call)
allocating. Each call did newStackFrameSet() -- a StackFrameSet plus its
initial StackFrame (a slice and a map) -- AND, worse, prepended it with
append([]*StackFrameSet{head}, sets...), allocating a fresh backing slice and
copying the whole save-stack every call.
Two changes:
- Treat the frameset save-stack as a tail stack (append to push, truncate to
pop) instead of prepending at index 0. get/set only ever touch the cached
head, so list order is irrelevant; this removes the per-call slice
realloc + O(depth) copy.
- Pool popped framesets (LIFO) and reset-and-reuse them on the next push,
mirroring the per-frameset frame free list. A reset trims back to one
cleared base frame (extras go to the frame pool). After warmup, repeated
calls allocate no framesets or frames.
Measured (big.csv, 1M rows, best of 5):
put, 2 nested func calls/record: 2.73 -> 1.87 (~31%)
GC cycles 25 -> 16; newStackFrameSet/newStackFrame fall out of the allocation
profile entirely. (chain-1 etc. have no UDFs and are unaffected.)
Verified: go test ./pkg/... and full regression suite pass; recursion
(fact/fib), local-scope isolation, and subroutine+oosvar all correct.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Drop redundant deep-copy of UDF return values (~3-16% on UDF put)
A user-defined function's return value was deep-copied twice on the way out:
once in ReturnNode.Execute (returnValue.Copy() when building the block-exit
payload) and again in UDFCallsite.EvaluateWithArguments
(blockReturnValue.Copy() at the end).
The ReturnNode copy is the necessary one: it detaches the value from the
callee's frame so it survives the frame being popped (and, since perf-try-7,
pooled/reused). By the time EvaluateWithArguments returns, blockReturnValue is
therefore already an independent deep copy, so the second copy is pure waste --
and callers that retain the result copy again anyway (field/oosvar/local
assignment all PutCopy/Copy). The other return paths (implicit-absent, error)
don't use blockReturnValue, so this only affects the BLOCK_EXIT_RETURN_VALUE
path.
Return blockReturnValue directly.
Measured (big.csv, 1M rows, best of 5):
put, 2 nested scalar-returning calls/record: 1.89 -> 1.83 (~3%)
put, map-returning func per record: 2.34 -> 1.97 (~16%)
Win scales with return-value size (the avoided copy is deep). All UDF/HOF
callsites (apply/reduce/sort/select/fold/...) go through this path.
Verified: go test ./pkg/... and full regression suite pass; recursion, HOFs,
and returned-map isolation (mutating a returned map does not affect a
subsequent call) all correct.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Bind scalar locals/params by reference, not by copy (~4-9% on DSL)
NewTypeGatedMlrvalVariable and TypeGatedMlrvalVariable.Assign deep-copied every
value bound to a local variable or function parameter -- ~6.9M allocations on a
UDF-heavy put. For scalars that copy is unnecessary:
Aliasing audit. Assignment everywhere REPLACES pointers rather than mutating
Mlrvals in place: Mlrmap.PutCopy reassigns pe.Value, Assign reassigns
tvar.value. The only in-place mutation a scalar undergoes is idempotent
type-inference caching (printrep -> typed). So a local/param bound by reference
to a scalar source can never observe its source change, and reassigning the
local replaces its own pointer without touching the source -- capture-by-value
semantics are preserved. Maps and arrays, by contrast, ARE mutated in place by
indexed assignment (m[k]=v), so an aliased collection would corrupt its source;
those must still be deep-copied.
So copyForBind copies only arrays/maps and binds scalars by reference. (Return
values are independently safe: ReturnNode.Execute still deep-copies them.)
Measured (big.csv, 1M rows, best of 5):
UDF-heavy put (scalar args/locals): 1.84 -> 1.68 (~9%)
x = $a+$b; $s = x*2 (no UDF): 0.50 -> 0.48 (~4%)
Verified: go test ./pkg/... and full regression suite pass, plus targeted
alias-then-mutate tests: scalar locals capture-by-value (source change after
bind not observed; reassigning one of two aliases leaves the other intact;
mutating a scalar param leaves the caller field intact), and collections stay
independent (local/param/oosvar-element map copies isolate in-place mutation).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|---|---|---|
| .. | ||
| context.go | ||
| doc.go | ||
| indexed-lvalues.md | ||
| mlrval_typing.go | ||
| README.md | ||
| slice_list.go | ||
This package contains types.Context and related stream types. The Mlrval and Mlrmap types used for record values and expression/variable values in the Miller put/filter DSL are implemented in the pkg/mlrval package.
Mlrval
The Mlrval structure (in package mlrval) includes string, int, float, boolean, array-of-mlrval, map-string-to-mlrval, void, absent, and error types as well as type-conversion logic for various operators.
- Miller's
absenttype is like Javascript'sundefined-- it's for times when there is no such key, as in a DSL expression$out = $foowhen the input record is$x=3,y=4-- there is no$fooso$foohasabsenttype. Nothing is written to the$outfield in this case. See also here for more information. - Miller's
voidtype is like Javascript'snull-- it's for times when there is a key with no value, as in$out = $xwhen the input record is$x=,$y=4. This is an overlap withstringtype, since a void value looks like an empty string. I've gone back and forth on this (including when I was writing the C implementation) -- whether to retainvoidas a distinct type from empty-string, or not. I ended up keeping it as it made theMlrvallogic easier to understand. - Miller's
errortype is for things like doing type-uncoerced addition of strings. Data-dependent errors are intended to result in(error)-valued output, rather than crashing Miller. See also here for more information. - Miller's number handling makes auto-overflow from int to float transparent, while preserving the possibility of 64-bit bitwise arithmetic.
- This is different from JavaScript, which has only double-precision floats and thus no support for 64-bit numbers (note however that there is now
BigInt). - This is also different from C and Go, wherein casts are necessary -- without which int arithmetic overflows.
- Using
$a * $bin Miller will auto-overflow to float. Using$a .* $bwill stick with 64-bit integers (if$aand$bare already 64-bit integers). - More generally:
- Bitwise operators such as
|,&, and^map ints to ints. - The auto-overflowing math operators
+,*, etc. map ints to ints unless they overflow in which case float is produced. - The int-preserving math operators
.+,.*, etc. map ints to ints even if they overflow.
- Bitwise operators such as
- See also here for the semantics of Miller arithmetic, which the
Mlrvalclass implements.
- This is different from JavaScript, which has only double-precision floats and thus no support for 64-bit numbers (note however that there is now
- Since a Mlrval can be of type array-of-mlrval or map-string-to-mlrval, a Mlrval is suited for JSON decoding/encoding.
Mlrmap
Mlrmap is the sequence of key-value pairs which represents a Miller record (implemented in package mlrval). The key-lookup mechanism is optimized for Miller read/write usage patterns -- please see mlrmap.go for more details.
It's also an ordered map structure, with string keys and Mlrval values. This is used within Mlrval itself.
Context
types.Context supports AWK-like variables such as FILENAME, NF, NR, and so on.
A note on JSON
- The code for JSON I/O is mixed between
Mlrvaland `Mlrmap. This is unsurprising since JSON is a mutually recursive data structure -- arrays can contain maps and vice versa. - JSON has non-collection types (string, int, float, etc) as well as collection types (array and object). Support for objects is principally in mlrmap_json.go; support for non-collection types as well as arrays is in mlrval_json.go.
- Both multi-line and single-line formats are supported.
- Callsites for JSON output are record-writing (e.g.
--ojson), thedumpandprintDSL routines, and thejson_stringifyDSL function.- The choice between single-line and multi-line for JSON record-writing is controlled by
--jvstackand--no-jvstack, the former (multiline) being the default. - The
dumpandprintDSL routines produce multi-line output without a way for the user to choose single-line output. - The
json_stringifyDSL function lets the user specify multi-line or single-line, with the former being the default,
- The choice between single-line and multi-line for JSON record-writing is controlled by