Greg Copeland <greg@copelandconsulting.net> writes:
> Ya, I'm currently looking to see how the memory is being used and why.
> I'm trying to better understand it's life cycle. You implying that even
> the short term memory should be using the palloc stuff? What about long
> term? Blanket statement that pretty much all the PLy stuff should
> really be using palloc?
Short-term stuff almost certainly should be using palloc, IMHO; anything
that is not going to survive the current function invocation should be
palloc'd in CurrentMemoryContext. The main reason for this is that you
don't need to fear leaking such memory if the function is aborted by
elog(). Depending on what you are doing, you may not have to bother
with explicit pfree's at all for such stuff. (In a PL handler you could
probably get away with omitting pfree's for stuff allocated once per
call, but not for stuff allocated once per statement. Unless you were to
make a new context that gets reset for each statement ... which might be
a good idea.)
For stuff that is going to live a long time and then be explicitly
freed, I don't think there's a hard-and-fast rule about which to use.
If you are building a complex data structure (parsetree, say) then it's
going to be easier to build it in a memory context and then just free
the context rather than tearing down the data structure piece-by-piece.
But when you are talking about a single object, there's not a heck of a
lot of difference between malloc() and palloc in TopMemoryContext.
I'd lean towards using the palloc routines anyway, for consistency of
coding style, but that's a judgment call not a must-do thing.
regards, tom lane