Skip to content
Myr

Improve performance of join/1 on large arrays (#3639)

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

join/1 folded each element as `(acc + $x) + elem`, with the element branch ending in `.//""`. Both leave a second live reference to the accumulator: the nested + feeds the same `.` to both operands, and the `//` leaves a forkpoint below it on the stack. `jvp_string_append` therefore cannot grow the accumulator in place, and copies the whole string once per element. Pipe `acc + $x` into `. + elem` and drop the `//`, since adding null to a string is already a no-op. join/1 is now linear: joining 8000 strings of 1000 chars goes from 6.5s to 0.06s, with output and error messages unchanged.

authored by Artem Lytkin · committed by GitHub · parent 32580f5 · Browse files · 2 files+12 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

2 files+12 added−2 removed

  • tests:+8 added−0 removed
  • other:+4 added−2 removed

2 files+12 added−2 removed

modified:src/builtin.jq+4 added-2 removed
61 unmodified lines
62def strings: select(type == "string");63def nulls: select(. == null);64def values: select(. != null);65def scalars: select(type|. != "array" and . != "object");66# Keep the accumulator the only reference on the left of + so the string is67# appended in place; a nested + or a // inside the reduce copies it every step.68def join($x): reduce .[] as $i (null;67 (if .==null then "" else .+$x end) +68 ($i | if type=="boolean" or type=="number" then tostring else .//"" end)69 (if .==null then "" else .+$x end) |70 . + ($i | if type=="boolean" or type=="number" then tostring end)71 ) // "";72def _flatten($x): reduce .[] as $i ([]; if $i | type == "array" and $x != 0 then . + ($i | _flatten($x-1)) else . + [$i] end);73def flatten($x): if $x < 0 then error("flatten depth must not be negative") else _flatten($x) end;74def flatten: _flatten(-1);
168 unmodified lines
modified:tests/jq.test+8 added
2074 unmodified lines
2075try join(",") catch .2076["1","2",[3,4,5]]2077"string (\"1,2,\") and array ([3,4,5]) cannot be added"20782079join("-")2080{"a":"x","b":1,"c":null,"d":false}2081"x-1--false"20822083try join(1) catch .2084["a","b"]2085"string (\"a\") and number (1) cannot be added"20862087{if:0,and:1,or:2,then:3,else:4,elif:5,end:6,as:7,def:8,reduce:9,foreach:10,try:11,catch:12,label:13,import:14,include:15,module:16}2088null2089{"if":0,"and":1,"or":2,"then":3,"else":4,"elif":5,"end":6,"as":7,"def":8,"reduce":9,"foreach":10,"try":11,"catch":12,"label":13,"import":14,"include":15,"module":16}2090
596 unmodified lines