Since #3633, `reduce` pushes a copy of its input before the `FORK`, and that copy stays in a slot saved by the `FORK` until the loop ends. When `init` holds `.`, as in `_assign` and `_modify`, the copy is a second reference to the accumulator, so the first `setpath` in each reduction copies the whole input. Building an object key by key with `.[$k] = $v`, `|=` or `+=` became quadratic again, the slowdown #618 reported and `DUPN` was added to fix. Store the input in a variable before the `FORK` and load it with `LOADVN` at the start of the loop instead. The slots saved by the `FORK` no longer refer to the input while the body runs, and the slot below `init` is still not popped destructively, so #3227 stays fixed.
This commit is contained in:
1 parent
3d3ee5a684
commit
d334411b9f
2 files changed
+14
-2
No files matched your search
+8
-2
@@ -832,7 +832,13 @@ static block bind_alternation_matchers(block matchers, block body) {
|
||||
|
||||
block gen_reduce(block source, block matcher, block init, block body) {
|
||||
block res_var = gen_op_var_fresh(STOREV, "reduce");
|
||||
block loop = BLOCK(source,
|
||||
// Keep the input in a variable rather than in a stack slot saved by the
|
||||
// FORK, so that it is not referenced while `body` updates the accumulator,
|
||||
// and leave the slot below `init` intact for `init` to backtrack (#3227).
|
||||
block input_var = gen_op_var_fresh(STOREV, "reduce_input");
|
||||
block loop = BLOCK(gen_op_bound(LOADVN, input_var),
|
||||
gen_op_simple(DUP),
|
||||
source,
|
||||
bind_alternation_matchers(matcher,
|
||||
BLOCK(gen_op_bound(LOADVN, res_var),
|
||||
body,
|
||||
@@ -842,9 +848,9 @@ block gen_reduce(block source, block matcher, block init, block body) {
|
||||
init,
|
||||
res_var,
|
||||
gen_op_simple(DUP),
|
||||
input_var,
|
||||
gen_op_target(FORK, loop),
|
||||
loop,
|
||||
gen_op_simple(POP),
|
||||
gen_op_bound(LOADVN, res_var));
|
||||
}
|
||||
|
||||
|
||||
@@ -2795,6 +2795,12 @@ null
|
||||
0
|
||||
1
|
||||
|
||||
# regression test for #3227 (reduce, non-empty source)
|
||||
reduce .[] as $x (0, 10; . + $x)
|
||||
[1, 2]
|
||||
3
|
||||
13
|
||||
|
||||
# regression test for #3227 (foreach)
|
||||
foreach .[] as $x (0, 1; . + $x)
|
||||
[1, 2]
|
||||
|
||||
Reference in new issue
Block a user