Skip to content
Myr

perf: avoid the intermediate array in from_entries (#3626)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Define `from_entries` as `add(.[] | f) // {}` instead of `map(f) | add // {}`. Since `add(f)` is `reduce f as $x (null; . + $x)`, both fold the same values in the same order from the same seed, so the only difference is that the array of single-key objects built by `map` is never materialized. Measured with both the generator and the result suppressed, so that only the `from_entries` work differs: 6-15% less user time across input shapes, which is 10-24% of what `from_entries` itself costs. For inputs above roughly a thousand entries, peak RSS drops by 37%, around 80% of the memory `from_entries` adds on top of its input; a 1,000,000 entry array goes from 1064 MiB to 672 MiB.

authored by A4-Tacks · committed by GitHub · parent 12cdd95 · Browse files · 1 file+2 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+2 added−2 removed

  • other:+2 added−2 removed

1 file+2 added−2 removed

modified:src/builtin.jq+2 added-2 removed
37 unmodified lines
38def recurse(f; cond): def r: ., (f | select(cond) | r); r;39def recurse: recurse(.[]?);4041def to_entries: [keys_unsorted[] as $k | {key: $k, value: .[$k]}];42def from_entries: map({ (.key // .Key // .name // .Name):43 if has("value") then .value else .Value end }) | add // {};42def from_entries: add(.[] | { (.key // .Key // .name // .Name):43 if has("value") then .value else .Value end }) // {};44def with_entries(f): to_entries | map(f) | from_entries;45def reverse: [.[range(length-1;-1;-1)]];46def indices($i): if type == "array" and ($i|type) == "array" then .[$i]47 elif type == "array" then .[[$i]]
193 unmodified lines