Re:Making a Go program 70% faster with a one character change
by amluto on Wednesday November 16, 2022 @12:38PM
(#33627106)
I haven't actually played with this, but if the same pattern of lazily (sloppily?) returning arbitrary pointers along with errors continues, the lifetime ought to be extended arbitrarily. The caller could itself return val, err, and so on up the chain.
Re:Making a Go program 70% faster with a one character change
by foldr on Wednesday November 16, 2022 @01:00PM
(#33627565)
I'm not seeing how that would cause a memory leak. It just means that the value might be GCed a bit later. Could you give an example?
Re:Making a Go program 70% faster with a one character change
by amluto on Wednesday November 16, 2022 @04:33PM
(#33630994)
It’s a temporary leak. My point is that it’s an actual side effect, unlike how in C it has no effect whatsoever if the value is ignored.
In a language where destruction of an object often releases external resources (C++, for example, or Python or Rust to a lesser extent), this effect would be more dramatic. Imagine someone doing this in Python:
def func():
f = tmpfile(…)
err = do something
return f, err
This style would be absurd and wrong — it keeps f alive to long.
The following toy example doesn't leak memory. Are you thinking of some other pattern that would leak memory? If so, what is it? I can only think of patterns where a logic error is also involved. That is, where the meaningless value of 'val' is used in code paths where err != nil.
You might think that you'd get a leak if the error branch was also long-lived, but Go's GC seems to be precise with respect to conditional branching (as far as I can tell by experimenting with runtime.SetFinalizer). That is, as long as the error branch doesn't refer to 'val', then the value pointed to by 'val' can be collected once the error branch is entered (and before 'caller' returns).