When should allocations be documented?

I’m making a PR to Base, and before the code there had avoidable allocations. I’m thinking mostly about Base, but people can answer about packages too.

If you have no allocations, ever, e.g. not dependent on code path, then I think you shouldn’t mention, it’s just implied no allocation.

If you always allocate then should it be documented? If it’s a function that can’t be done any other way, then they are ok, and IMHO implied, needs not be mentioned. People (can) also discover at runtime, those that want to avoid. But not all users are allocation-savvy and might want it documented?

If it’s code-path dependent, or just avoidable allocation, always, IMHO it should be mentioned. Or do people feel it clutters the docs?

Continuing the discussion from Case-insensitive prefix/suffix stripping:

If you use a chopprefix or chopsuffix, then you get a SubString back (or the full string if nothing chopped, then still a SubString type to be type-stable, no problem with that). This then wouldn’t strictly need to allocate if coded that way.

However replace in general is meant to replace even from a middle of a string and thus needs to allocate (theoretically there would be an obscure workaround… two concatenated SubStrings…). So I don’t expect it documented, even if when ^ or $ used, in effect emulating the other functions for that specific need.

The chop functions, if no regex is used do not allocate, but if you use a Regex they do, and then because of multiple dispatch they are technically different functions, though not all may realize that… It’s sort of like having code-dependent path within a function.

I’m not sure I totally follow, but I wouldn’t say this is true at all. A function that doesn’t document whether and what it allocates may allocate or not allocate. Most likely, it will allocate something, since writing completely non-allocating code requires a lot of care (or isn’t even possible in general). If you write a function that’s specifically not allocating, that’s a special feature, and you should document that (and also explicitly test it). If a function allocates some particular large objects, that’s also nice to mention in the documentation, of course.

5 Likes