You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
plpgsql: implement tail-call optimization for PLpgSQL routines
This patch implements tail-call optimization for the nested routine
execution that is used to handle PLpgSQL control flow. PLpgSQL sub-routines
are always tail calls because they are built as "continuation" functions,
so we can always use the optimization for PLpgSQL. Tail-call optimization
is only possible if the plan is not distributed (although we may not
currently distribute such plans anyway).
The optimization is performed by setting a `deferredRoutineReceiver`
field on the planner before planning and running a nested routine.
This `deferredRoutineReceiver` allows a routine in tail-call
position to send the information needed to evaluate itself to its
parent, and then return NULL. Once the parent routine receives the
result, it checks whether `deferredRoutineReceiver` received a
deferred nested routine, and if so, evaluates it to obtain the
actual result.
Given a simple looping function like the following:
```
CREATE FUNCTION f(n INT) RETURNS INT AS $$
DECLARE
i INT := 0;
BEGIN
LOOP
IF i >= n THEN
EXIT;
END IF;
i := i + 1;
END LOOP;
RETURN i;
END
$$ LANGUAGE PLpgSQL;
```
This optimization takes runtime on my machine for `n=100000` from >20m
to ~2s.
Informs cockroachdb#105254
Release note: None
0 commit comments