Creating PostgreSQL Arrays Without A Quadratic Blowup
blog.heapanalytics.com
blog.heapanalytics.com
Actually they don't. You can not resize a (static) array. What you really want is a dynamic array, an array list or whatever you like to call it. In this case you can double the size of the underlying array when you have to reallocate it and get the amortized runtime down but at the price of using up to twice the memory you need.
Maybe array_append is to blame because its pure existence somewhat implies that you are working with array lists and not with arrays.
Yeah, I've never read a line of PLPGSQL before this, but I can tell by the assignment operator := that this is obviously creating a copy of the array every time you add an element to the array. This would also cause a quadratic blowup and/or a memory blowup in any other language I've heard of, not just PLPGSQL. Anyone who has taken an introductory algorithms & data structures class really should know better than to write code like this.
So your inference is, in fact, incorrect. The assignment must make a logical copy, but this does not have to involve making a physical copy.
I think these techniques should be standard practice in programming language implementations.
[0] http://stackoverflow.com/questions/3271256/implement-an-immu...
Edit: my mistake, PostgreSQL calls them "relations."
I haven't used postgres, but this seems like trying to use a write-once-optimized structure for append-heavy use. Is it actually faster? And if so, since this is used for funnel-queries, is the query-speedup worth the write-slowdown, given what I would expect are much higher write loads than read loads, and that writes probably have to happen quickly while reads do not?
That being said an array should be even faster than a lookup to a secondary table with real clustered index since the array data would be in the row data of the main table incurring only the offset lookup to retrieve. There are definitely cases where hierarchical data structures are superior in performance to normalized ones. You gotta watch out though for hierarchical structures that store keys inline as the add their own space and I/O overhead (See shortening key names in Mongo DB). Arrays are a good choice though, they allow multi-value data inline without key overhead.
I think what this is is a translation of a classic OO "array.add(x)", which would usually be O(1), into "array = array + x", because that's the closest you can get in this language. However, mapping that translation back into a language you know, that should raise alarm bells, because it looks like it should be O(n) and allocate garbage like mad.
So, rather, i think this is classic insufficient paranoia and self-doubt when doing an unfamiliar new thing.