Re: Is array_append O(n)?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Rob Nikander <rob(dot)nikander(at)gmail(dot)com>
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Is array_append O(n)?
Date: 2019-06-18 17:47:42
Message-ID: 15730.1560880062@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Rob Nikander <rob(dot)nikander(at)gmail(dot)com> writes:
> On Jun 18, 2019, at 7:37 PM, Alvaro Herrera <alvherre(at)2ndquadrant(dot)com> wrote:
>> On 2019-Jun-18, Rob Nikander wrote:
>>> Does `array_append(arr, elt)` create a new array and copy everything?
>>> In other words, is it O(n) or O(1)? […]

>> Starting with 9.5, there's an optimization that I think is supposed to
>> make it O(1):

> Sweet! Thanks. Now I’d like to know how to tell if that optimization is being used, or not.

Time it and see ;-)

From memory, the cases that should be fast now are

* Assigning to an element of a plpgsql variable that is an array,
ie "arrayvar[n] := newelement".

* "arrayvar := arrayvar || newarrayelement". I think it doesn't
matter whether you use operator or function-call syntax.

> Same question for the a way to pop an element off the end in O(1) time.

Offhand I don't remember any optimization for that, but I might be
wrong. Looking at the comments in the plpgsql portion of the
aforementioned commit would probably give more info.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Rob Nikander 2019-06-18 18:02:24 delete inside for plpgsql loop on same relation?
Previous Message Miles Elam 2019-06-18 17:14:00 Re: Inserts restricted to a trigger