pgsql: Represent Lists as expansible arrays, not chains of cons-cells. - Mailing list pgsql-committers

From Tom Lane
Subject pgsql: Represent Lists as expansible arrays, not chains of cons-cells.
Date
Msg-id E1hn4zJ-0002EL-IS@gemulon.postgresql.org
Whole thread Raw
Responses Re: pgsql: Represent Lists as expansible arrays, not chains ofcons-cells.  (Michael Paquier <michael@paquier.xyz>)
List pgsql-committers
Represent Lists as expansible arrays, not chains of cons-cells.

Originally, Postgres Lists were a more or less exact reimplementation of
Lisp lists, which consist of chains of separately-allocated cons cells,
each having a value and a next-cell link.  We'd hacked that once before
(commit d0b4399d8) to add a separate List header, but the data was still
in cons cells.  That makes some operations -- notably list_nth() -- O(N),
and it's bulky because of the next-cell pointers and per-cell palloc
overhead, and it's very cache-unfriendly if the cons cells end up
scattered around rather than being adjacent.

In this rewrite, we still have List headers, but the data is in a
resizable array of values, with no next-cell links.  Now we need at
most two palloc's per List, and often only one, since we can allocate
some values in the same palloc call as the List header.  (Of course,
extending an existing List may require repalloc's to enlarge the array.
But this involves just O(log N) allocations not O(N).)

Of course this is not without downsides.  The key difficulty is that
addition or deletion of a list entry may now cause other entries to
move, which it did not before.

For example, that breaks foreach() and sister macros, which historically
used a pointer to the current cons-cell as loop state.  We can repair
those macros transparently by making their actual loop state be an
integer list index; the exposed "ListCell *" pointer is no longer state
carried across loop iterations, but is just a derived value.  (In
practice, modern compilers can optimize things back to having just one
loop state value, at least for simple cases with inline loop bodies.)
In principle, this is a semantics change for cases where the loop body
inserts or deletes list entries ahead of the current loop index; but
I found no such cases in the Postgres code.

The change is not at all transparent for code that doesn't use foreach()
but chases lists "by hand" using lnext().  The largest share of such
code in the backend is in loops that were maintaining "prev" and "next"
variables in addition to the current-cell pointer, in order to delete
list cells efficiently using list_delete_cell().  However, we no longer
need a previous-cell pointer to delete a list cell efficiently.  Keeping
a next-cell pointer doesn't work, as explained above, but we can improve
matters by changing such code to use a regular foreach() loop and then
using the new macro foreach_delete_current() to delete the current cell.
(This macro knows how to update the associated foreach loop's state so
that no cells will be missed in the traversal.)

There remains a nontrivial risk of code assuming that a ListCell *
pointer will remain good over an operation that could now move the list
contents.  To help catch such errors, list.c can be compiled with a new
define symbol DEBUG_LIST_MEMORY_USAGE that forcibly moves list contents
whenever that could possibly happen.  This makes list operations
significantly more expensive so it's not normally turned on (though it
is on by default if USE_VALGRIND is on).

There are two notable API differences from the previous code:

* lnext() now requires the List's header pointer in addition to the
current cell's address.

* list_delete_cell() no longer requires a previous-cell argument.

These changes are somewhat unfortunate, but on the other hand code using
either function needs inspection to see if it is assuming anything
it shouldn't, so it's not all bad.

Programmers should be aware of these significant performance changes:

* list_nth() and related functions are now O(1); so there's no
major access-speed difference between a list and an array.

* Inserting or deleting a list element now takes time proportional to
the distance to the end of the list, due to moving the array elements.
(However, it typically *doesn't* require palloc or pfree, so except in
long lists it's probably still faster than before.)  Notably, lcons()
used to be about the same cost as lappend(), but that's no longer true
if the list is long.  Code that uses lcons() and list_delete_first()
to maintain a stack might usefully be rewritten to push and pop at the
end of the list rather than the beginning.

* There are now list_insert_nth...() and list_delete_nth...() functions
that add or remove a list cell identified by index.  These have the
data-movement penalty explained above, but there's no search penalty.

* list_concat() and variants now copy the second list's data into
storage belonging to the first list, so there is no longer any
sharing of cells between the input lists.  The second argument is
now declared "const List *" to reflect that it isn't changed.

This patch just does the minimum needed to get the new implementation
in place and fix bugs exposed by the regression tests.  As suggested
by the foregoing, there's a fair amount of followup work remaining to
do.

Also, the ENABLE_LIST_COMPAT macros are finally removed in this
commit.  Code using those should have been gone a dozen years ago.

Patch by me; thanks to David Rowley, Jesper Pedersen, and others
for review.

Discussion: https://postgr.es/m/11587.1550975080@sss.pgh.pa.us

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/1cff1b95ab6ddae32faa3efe0d95a820dbfdc164

Modified Files
--------------
contrib/file_fdw/file_fdw.c               |   9 +-
contrib/pg_trgm/trgm_regexp.c             |  18 +-
contrib/postgres_fdw/deparse.c            |   6 +-
contrib/sepgsql/label.c                   |  11 +-
contrib/sepgsql/uavc.c                    |   9 +-
src/backend/access/common/printtup.c      |   4 +-
src/backend/catalog/heap.c                |   2 +-
src/backend/catalog/index.c               |   6 +-
src/backend/catalog/namespace.c           |   6 +-
src/backend/catalog/partition.c           |   2 +-
src/backend/catalog/pg_inherits.c         |  14 +-
src/backend/catalog/pg_proc.c             |  10 +-
src/backend/catalog/pg_publication.c      |  12 +-
src/backend/commands/analyze.c            |   3 +-
src/backend/commands/async.c              |  26 +-
src/backend/commands/createas.c           |   4 +-
src/backend/commands/explain.c            |   2 +-
src/backend/commands/foreigncmds.c        |   7 +-
src/backend/commands/indexcmds.c          |   2 +-
src/backend/commands/prepare.c            |   2 +-
src/backend/commands/seclabel.c           |   2 +-
src/backend/commands/tablecmds.c          |  65 +--
src/backend/commands/tsearchcmds.c        |  12 +-
src/backend/commands/view.c               |   2 +-
src/backend/executor/execJunk.c           |   2 +-
src/backend/executor/execPartition.c      |   2 +-
src/backend/executor/execUtils.c          |   2 +-
src/backend/executor/functions.c          |   2 +-
src/backend/executor/nodeTableFuncscan.c  |   2 +-
src/backend/libpq/auth.c                  |   6 +-
src/backend/libpq/hba.c                   |  16 +-
src/backend/nodes/copyfuncs.c             |  44 +-
src/backend/nodes/list.c                  | 816 +++++++++++++++++-------------
src/backend/nodes/nodeFuncs.c             |   4 +-
src/backend/nodes/outfuncs.c              |   2 +-
src/backend/nodes/print.c                 |   4 +-
src/backend/optimizer/geqo/geqo_eval.c    |   7 +-
src/backend/optimizer/path/allpaths.c     |   4 +-
src/backend/optimizer/path/costsize.c     |  12 +-
src/backend/optimizer/path/equivclass.c   |  38 +-
src/backend/optimizer/path/indxpath.c     |  53 +-
src/backend/optimizer/path/joinrels.c     |  46 +-
src/backend/optimizer/path/pathkeys.c     |   6 +-
src/backend/optimizer/plan/analyzejoins.c |  29 +-
src/backend/optimizer/plan/createplan.c   |   9 +-
src/backend/optimizer/plan/planner.c      |  16 +-
src/backend/optimizer/plan/subselect.c    |   2 +-
src/backend/optimizer/prep/prepjointree.c |  22 +-
src/backend/optimizer/prep/preptlist.c    |   4 +-
src/backend/optimizer/prep/prepunion.c    |   4 +-
src/backend/optimizer/util/clauses.c      |   2 +-
src/backend/optimizer/util/paramassign.c  |  17 +-
src/backend/optimizer/util/pathnode.c     |  51 +-
src/backend/optimizer/util/plancat.c      |   4 +-
src/backend/optimizer/util/predtest.c     |  12 +-
src/backend/optimizer/util/tlist.c        |  12 +-
src/backend/parser/analyze.c              |   2 +-
src/backend/parser/gram.y                 |  13 +-
src/backend/parser/parse_agg.c            |   4 +-
src/backend/parser/parse_coerce.c         |   8 +-
src/backend/parser/parse_collate.c        |   6 +-
src/backend/parser/parse_cte.c            |   8 +-
src/backend/parser/parse_expr.c           |   6 +-
src/backend/parser/parse_func.c           |  16 +-
src/backend/parser/parse_relation.c       |  31 +-
src/backend/parser/parse_target.c         |  24 +-
src/backend/parser/parse_utilcmd.c        |   2 +-
src/backend/partitioning/partbounds.c     |  17 +-
src/backend/partitioning/partprune.c      |  17 +-
src/backend/replication/basebackup.c      |   2 +-
src/backend/replication/syncrep.c         |  12 +-
src/backend/storage/sync/sync.c           |  12 +-
src/backend/tcop/postgres.c               |   4 +-
src/backend/tcop/pquery.c                 |   2 +-
src/backend/tcop/utility.c                |   4 +-
src/backend/utils/adt/jsonpath_exec.c     |  10 +-
src/backend/utils/adt/jsonpath_gram.y     |   8 +-
src/backend/utils/adt/partitionfuncs.c    |  34 +-
src/backend/utils/adt/ruleutils.c         |  32 +-
src/backend/utils/adt/selfuncs.c          |  13 +-
src/backend/utils/cache/partcache.c       |   2 +-
src/backend/utils/cache/relcache.c        |   2 +-
src/backend/utils/init/postinit.c         |   4 +-
src/backend/utils/mb/mbutils.c            |  12 +-
src/include/nodes/pg_list.h               | 566 ++++++++++++++-------
src/pl/plpgsql/src/pl_exec.c              |   2 +-
86 files changed, 1248 insertions(+), 1115 deletions(-)


pgsql-committers by date:

Previous
From: Thomas Munro
Date:
Subject: pgsql: Provide XLogRecGetFullXid().
Next
From: Peter Geoghegan
Date:
Subject: pgsql: Fix pathological nbtree split point choice issue.