We should clarify that what
@timereports is specifically heap allocations, which are typically needed for either mutable objects or for creating/growing variable-sized containers (such asArrayorDict, strings, or “type-unstable” objects whose type is only known at runtime). Allocating (or deallocating) such blocks of memory may require an expensive system call (e.g. viamallocin C), and they must be tracked for garbage collection. In contrast, immutable values like numbers (except bignums), tuples, and immutablestructs can be stored much more cheaply, e.g. in stack or CPU-register memory, so one doesn’t typically worry about the performance cost of “allocating” them.Unexpected memory allocation is almost always a sign of some problem with your code, usually a problem with type-stability or creating many small temporary arrays. Consequently, in addition to the allocation itself, it’s very likely that the code generated for your function is far from optimal. Take such indications seriously and follow the advice below.
12 Likes