New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: arena: new package providing memory arenas #51317
Comments
What is the reason to add this to the standard library as opposed to building a third party package? |
Your specification says:
If I read it correctly, this means that it is permitted to keep pointers into a released arena (i.e. stray pointers) as long as you do not explicitly dereference them. However, this means that the compiler must now be careful not to dereference any pointer it knows not to be If the rules were tightened to say that you have to erase all pointers into an Another benefit is that it's less likely to have tricky edge cases where stray pointers could remain in some data structures (e.g. as the result of some string manipulation or With this issue addressed, I'm very interested in this proposal. It will be very useful for complex temporary data structures that need to be built step by step and deallocated all at once. |
@hherman1 as far as i understood this proposal, there are a lot of troubles for example in appending to slices, e.g. the code could be more readable if you just use Even though, the idea to manualy handle memory freeing sounds great for me, cause there are a lot of specific cases, when you don't want to hope on the garbage collector |
I'd be curious to understand the problems that an arena solves that can't be solved by either using sync.Pool, allocating a slice of a given type (for example a binary tree allocating a slice of nodes), or a combination of both techniques. It seems to me that Go provides idiomatic ways of addressing at least the specific protobuf use-case mentioned here. In addition to the above, doesn't the Go allocator already have sizes classes? If the proposal does proceed, I think we need to see a prototype outperform the runtimes allocator and is enough gain to justify the ecosystem complexity. |
What's the main usecase for wanting to allocate types created via reflect in arenas? Marshalling & unmarshall?
Is there a hurry in adding arenas? It can always wait one or two release cycles before been added so that people are ready with generics. |
This proposal sounds really good to me from a user's perspective, but one detail causes concern: wouldn't something like all code eventually end up needing arena support? For example, imagine I have a web service where I want to allocate an arena for each web request. This sounds like a great use case for this, but I'd need |
It's hard to do this safely in a third party package. Consider a struct allocated in the arena that contains pointers to memory allocated outside the arena. The GC must be aware of those pointers, or it may incorrectly free ordinary-memory objects that are still referenced by arena objects. A third party package would have to somehow make the garbage collector aware of those pointers, including as the pointer values change, which is either hard or inefficient. |
That is already true. Go code can use pointers that point to memory that was allocated by C, or that was allocated by
I believe that we can already do that. If the garbage collector sees a pointer to a freed arena, it can crash the program. If we have two complete GC cycles after an arena is freed, we can know for sure that there are no remaining pointers into that address space, and we can reclaim the addresses. However, I don't know if the current patches implement that. |
As you note,
I'm not sure how size classes are related. As @danscales mentions, there is already an implementation, which is in use internally at Google. It does overall outperform the runtime allocator for cases like RPC servers that transmit data as protobufs. |
First, I feel this should live in the Also, a question for clarification:
One of the main usecases mentioned is protobuf decoding. ISTM that, if every call to
AIUI the proposal would not interoperate with |
Yes, marshaling and unmarshaling. These cases are compelling for, for example, network RPC servers that must serialize and unserialize data for every request. |
One implementation caveat: a 64-bit address space isn't quite the inexhaustible vastness it first seems because many environments impose tighter restrictions. (I recently used a 4GB mmap as an optimization but found OpenBSD's default ulimit is 1.5GB and some users seem to impose their own limits.) |
Which reminds me:
Does this mean this package would use build-tags to limit itself to 64-bit architectures? And would programs using this then not run on 32-bit platforms, unless they specifically code around that? Also, this seems all the more reason to put this into |
Hi @Merovius, my interpretation was that the API could be implemented everywhere, but it would not increase efficiency everywhere:
|
@thepudds ah thank you, I missed that, alleviates my concerns around portability. Though I'd find it a bit confusing to provide the API without actual arenas. But, fair enough. |
@Merovius raises an interesting question, though, around what the overhead of the non-arena implementation of the arena api would be… |
Assuming the problem with protobufs is the actual objects and not some internal buffer, here is how I would naively use Today you might see code like this: book := &pb.AddressBook{} Rather I would suggest the generated book := NewAddressBook() The protoc generated code in its package would look something like this: var addressBookPool sync.Pool = sync.Pool{
New: func() interface{} {
return new(AddressBook)
},
}
func NewAddressBook() *AddressBook {
return addressBookPool.Get().(*AddressBook)
}
func (ab *AddressBook) Close() error {
*ab = AddressBook{}
addressBookPool.Put(ab)
return nil
} I assume if arena existed similar changes to have a constructor that uses it would need to happen as well? If not that burden would fall to the object creator which is in fact how I use sync.Pool with protobufs today (when needed) Now maybe more is needed say: func (ab *AddressBook) Close() error {
ab.closeOnce.Do(func() {
*ab = AddressBook{}
addressBookPool.Put(ab)
})
return nil
} Or maybe we need to also generate and use pools/constructors of But I would like to understand why the arena approach is better. I'd also be curious to bench an arena prototype against |
In addition to what Ian already said about the compiler not dereferencing stray pointers: One reason that we would like to able to deal with pointers to objects in the arena staying around after it freed (as long as they are not used) is because it may be quite tricky and disruptive to have to remove them from the stack. A pointer to an object in the arena could have been passed around as an arg and is still on the stack as an argument or local variable, but will not be used again. It would be good to ensure that the programmer does not have to nil out these pointers on the stack just to satisfy arenas, when they will naturally go away later. |
Yes, I agree. There's no rush to figure out and add arenas, so it may be worth waiting to use the generics API if there's consensus on it being a better API. The first point does remain - which is that we would prefer to have some API that allows for allocating a type that is created/calculated at runtime. However, the generics API could become the main API, and the one that allows for dynamic types could be the secondary API. |
Yes, that's a good point. If we have a package that is allocating lots of memory (often by doing decoding of wire format) and we want to use arenas with it, then we will have to plumb in a way to send down an optional allocator function that it should use if enabled (in our case, the allocator function would use an arena). That's what we have prototyped for the protobuf unmarshaling library calls (see last section). I don't see any easy way to make packages use arenas, but open to suggestions. |
Hi @danscales
Is there a rough estimate of how many new APIs this might translate to in the standard library, for example? |
Yes, that is true. It is possible there is another implementation that could deal with that many arenas simultaneously. But I will note that if you have 100s of requests in flight at one time, then they may not be allocating that much new data while serving each individual request, so arenas may not really be required in that case. Arenas are really more useful/appropriate for unmarshalling large data objects for which you may do a lot of processing. sync.Pool may be more appropriate if the allocated data per request is small (since there may also be only a limited number of known object types). |
Is there any idea of (A) what is the net cost of doing this with reflection and (B) will it be possible to not do it with reflection when using the generics API?
What message sizes/throughputs was the prototype tested at? Many small requests/responses is certainly the norm in my background, but I know google was looking hard (I believe?) a Vitess blog post that mainly dealt with very large data replication messages. Certainly if proto performance gets worse than status quo at high throughput levels, many people wouldn't be thrilled with that. |
Add memory allocator to context? It seems really silly but doing a second round of "context-aware" updates to add context in more places seems better to me than doing a second round of "context-aware" updates that adds an entirely new type of object that ends up needing to be sent everywhere. |
Hi all, One quick thought: could you utilize the write barrier that is currently used by the compiler/GC to detect writes to arena allocated memory outside of the arena. Then on .Free, copy the values that are referenced out to the main heap? This would let you effectively use an arena as a large scratch area, with the GC assisting in figuring out which values are not just scratch. |
Is the code for the experimental protobuf implementation published? The scope of code that needs changing in order to take advantage of per-request arenas seems huge, but I'm eager to see a real world example in hopes I'm wrong! |
@tarndt A protobuf message can include many different messages (as they are called) arranged in a complex memory layout. This is all relatively seamless for the program but it means that unmarshaling a protobuf isn't just a matter of allocating a single object type, it can involve dozens of different types. So you would need dozens of different Frankly an arena sounds a lot simpler. And let's not forget that an arena lets you notify the runtime exactly when the memory is no longer needed. A pool will stick around in a much less predictable fashion. |
The slice inside the *big.Float needs to be allocated from the arena for there to be any benefit. If I try to copy the result inside the Run/Call function, then the destination needs to allocate a new slice to hold that copy, and that slice would be in the arena, so it is invalid once the call returns. If I don't, then the result to copy from is invalid once the call returns, and I never have an opportunity to copy it. In general, that kind of API requires that every type which internally contains allocated memory provide ways to predict the amount of memory required and to copy that internal memory out to another object. If either is impossible, then that type can never be used inside an arena call. |
I agree with the concern/worry about rolling out arenas and would like to make the following concrete declarations:
Effectively, arenas represent an "attractive nuisance" because they are extremely valuable for a common "low-skill" use case but require intermediate-level knowledge (and, depending on how your organization uses request & response objects, may require bizarre tribal knowledge to know you can't do X with Y variable, miles away from where the arena is actually used). Object Pools were not demanded for encoding/json because Object Pools could not be used, really, in encoding/json. Arenas can, and anyone who has a Go HTTP surface running at high scale could measure the value of doing so in the tens of thousands of dollars, and potentially a lot more. My hope is that arenas aren't just put to work on whatever bespoke google use case drove the desire to implement them and set aside, because I think that this experiment has revealed (A) that go's tools for avoiding allocations are very thin on the ground for a language that chose to up-front garbage collector costs, and that (B) the reason for that is deep in the language and requires some attention. Taking an ambitious approach on delivering arenas could have major positive implications for go performance far beyond the narrow scope of arenas. |
This makes sense to me and does seem like a problem.
This is what my alternate API was meant to address. If perhaps there was some way to flag the result, and everything used to compose the result, must not be allocated in the arena, and everything else should be. That way you can have the single thing, the deserialized protobuf or what have you, which is reusable once the arena closes, and all other temporary memory is released. |
My understand of the proto decoder is that all of the allocations done during deserialization are things reachable from the return value. It only allocates things it needs to return; there are no temporary allocations. |
if some object are very sure be allocate.use.free in one function, then it should obviously be allocated in stack. |
I'd like to suggest an improvement to a potentially common case, where arenas are used in the preamble to request processing, e.g. when deserializing an incoming request:
Here the arena lives for the duration of handling the request which could, in certain contexts, take hundreds of ms, even though allocation from the arena completes within in a fraction of the total time. This means that the partial block the arena is holding cannot be reused until completion, despite there being no need to retain the unallocated memory from it. It's proposed that calling This has a couple benefits, albeit admittedly minor. First, it reduces the total number of active partial blocks, especially in cases where the total allocation amounts are small per request. This means the footprint would be marginally smaller, which may have benefits in certain contexts. Second, it may actually improve GC overhead--despite the number of arena memory allocations remaining the same--when dealing with a bursty workloads. Since the partial blocks will be rotated more quickly, the total number of new block allocations should be reduced. If the workload processes the burst and returns to a lower steady state, we again see fewer active blocks. The existing implementation would require a change to the current tracking of partial blocks by adding a reference count, and a boolean to indicate when they are "full". |
Maybe I'm way off-base here, but it seems to me that a cross between the two could solve some of those issues. For example, package unsafe
type Arena ...
func NewArena() *Arena
func (a *Arena) Free()
func (a *Arena) Use(f func())
This would allow, for example, easy usage with Edit: Should also be noted that a top-level function, if not provided, could easily be written by a user to simplify the common case: func FromArena[T any](a *unsafe.Arena, f func() T) (v T) {
a.Use(func() { v = f() })
return
} I don't think a function like that makes sense clogging up Edit 3: It occurs to me that the use-arenas-in-a-function approach could also potentially fix the issue of usage of an arena internally to something. It would remove the need to pass an arena to something because the system could just see when |
Edit: this comment was rude and out of line. I apologize to all involved and am now removing myself from the conversation. |
The problem with arena.Use is the problem with arenas more generally. If I make code that receives a pointer and does [thing] it's impossible for me to know that the pointer is allocated on an arena and can't be safely held somewhere. People forgetting to free arenas isn't a problem IMO and explicitly choosing an allocator and passing it as a parameter (perhaps via Context or something) is more in line with existing Go standards. On the converse, I don't think that prioritizing use cases where someone wants to hold arena-allocated objects long term is a good idea since that is contrary to the concept of an arena, whose lifetime is supposed to be limited by scope. I acknowledge that rolling snapshot storage of arbitrary key/value pairs probably requires something like that in order to be tenable, though. Maybe an unsafe method could be used to allow long-term storage of arena-allocated objects, but a TLSF or Ring Buffer allocator that itself has a long lifetime and whose objects are only permitted to be stored in or around itself might be a better fit than an arena for this use case. This is kind of what I mean about us needing to open a path to more types of allocation-avoiding tools. EDIT: What I mean by the above is, we finally get a single square peg and people are trying to cram it into round holes because it's the only peg we have. |
Perhaps the answer would be to simply have the danger of handling one of these pointers be signaled by the type system. Some sort of indicator that can only be removed by the |
FWIW that seems extremely close to the idea of Rust lifetimes and it seems fraught to me, to special case that into the type system for arenas. |
It would be a massive pain in the ass, but the alternative seems to be "allocations are largely unavoidable in our language that pays all GC fees up front" which doesn't seem very good either. |
it is really cool if go compiler can support to check lifetimes and further delete short lived objects. |
This is more or less what escape analysis allows for, and the Go compiler already does it. In other words, if the compiler can determine that a value doesn't escape the stack frame it was created in, it gets to be allocated on the stack (for the most part), and it is never managed by the GC[1]. Of course, escape analysis has room for improvement, and such improvements are another direction we could pursue in the space of designs to reuse memory more efficiently. [1] Stacks still need to be scanned, but only when a GC's mark phase is active. By putting values on the stack instead of the heap, however, the GC's mark phase happens less frequently. |
@mknyszek While from what I saw in this arena proposal, the New function return a regular go pointer.
I suppose a new pointer type or hint could improve both above concens. Let me call it weak ref.
|
@hauntedness Honest question: in what ways would this new weak pointer be different from unsafe.Pointer? Could we perhaps require the use of unsafe.Pointer for arenas? |
@beoran not OP but from what I understand of their suggestion, an unsafe.Pointer is not typed. What they seem to suggest is that pointers into an Arena should keep that information with them so that their scope/lifetime (which merges with the scope/lifetime of the objects these pointers are a part of) can be tracked (probably conservatively because of branching statements such as defer, goto, if etc). Also, by indirection, taking a reference to such arena pointing objects could/would extend their lifetime? It seems it would be a bit of a similar logic to definite assignment or typestate tracking where a variable of a given type has additional implicit/hidden mutable information/state that one may want to track (if relevant and possible). |
From the comments I think the Go team is worried about the abuse of |
@atdiar I see. Then, I think we could probably add a generic type arena.Pointer[T any] that does this. Perhaps with some compiler assistance. |
I think there is a misunderstanding about the concern with arenas. A substantial chunk of the "load more" bin is a discussion about whether arenas would change the memory safety properties of the language. The conclusion is that arenas are less unsafe than sync.Pool: they have the same failure modes, but misuse of arenas tends to fail loudly. At this point, the concern is about how often arenas will appear in APIs that otherwise don't seem to need to care. This means the arena.Pointer[T] idea only exacerbates the problem. You'd need to use it wherever you use any pointer, because that memory might have originally come from an arena. Otherwise you don't have arena support. |
@beoran just like @zephyrtronium indicates, I think that it shouldn't be visible to the end user here (that would complicate assignment rules too much otherwise, perhaps, although that could possibly be one solution with subtyping extended to non-interface types). So more similar to escape analysis |
I can not agree with the idea that it is not appeared often so we don't need to care. If it is not that often why bring this arena to go? API is not a lighthouse in language. we can't rely on common sense about how to use arena. Also, current situation is people looking at arena for performant usage. What they really need are avoid gc for performance and strong type system for safety and convenience. |
@hauntedness I think you misunderstood me. I did not mean that arenas will be rare. Exactly the opposite, in fact: I meant that arenas may be too common. APIs will need to add support for them so that users can tie those APIs' resources to the arenas they want for performance, even in places where those APIs don't themselves care. |
sir,please tell us the detail about "This proposal is on hold indefinitely due to serious API concerns. " |
Is there any plan to make this feature stable or deprecated? |
@choleraehyq Any decision will be mentioned here. No decision has been made, nor is any likely to be made any time soon. |
Note, 2023-01-17. This proposal is on hold indefinitely due to serious API concerns. The GOEXPERIMENT=arena code may be changed incompatibly or removed at any time, and we do not recommend its use in production.
Proposal: arena: new package providing memory arenas
Author(s): Dan Scales (with input from many others)
Last updated: 2022-2-22
Discussion at https://golang.org/issue/51317
Abstract
We propose implementing memory arenas for Go. An arena is a way to allocate a set of memory objects all from a contiguous region of memory, with the advantage that the allocation of the objects from the arena is typically more efficient than general memory allocation, and more importantly, the objects in the arena can all be freed at once with minimal memory management or garbage collection overhead. Arenas are not typically implemented for garbage-collected languages, because their operation for explicitly freeing the memory of the arena is not safe and so does not fit with the garbage collection semantics. However, our proposed implementation uses dynamic checks to ensure that an arena free operation is safe. The implementation guarantees that, if an arena free operation is unsafe, the program will be terminated before any incorrect behavior happens. We have implemented arenas at Google, and have shown savings of up to 15% in CPU and memory usage for a number of large applications, mainly due to reduction in garbage collection CPU time and heap memory usage.
Background
Go is a garbage-collected language. Application code does not ever explicitly free allocated objects. The Go runtime automatically runs a garbage-collection algorithm that frees allocated objects some time after they become unreachable by the application code. The automatic memory management simplifies the writing of Go applications and ensures memory safety.
However, large Go applications spend a significant amount of CPU time doing garbage collection. In addition, the average heap size is often significantly larger than necessary, in order to reduce the frequency at which the garbage collector needs to run.
Non-garbage-collected languages also have significant memory allocation and de-allocation overhead. In order to deal with complex applications where objects have widely varying lifetimes, non-garbage-collected languages must have a general-purpose heap allocator. Because of the differing sizes and lifetimes of the objects being allocated, such an allocator must have fairly complex code for finding memory for a new object and dealing with memory fragmentation.
One approach to reducing the allocation overhead for non-garbage-collected languages is region-based memory management, also known as arenas. The idea is that applications sometimes follow a pattern where a code segment allocates a large number of objects, manipulates those objects for a while, but then is completely done with those objects, and so frees all (or almost all) of the objects at roughly the same time. The code segment may be allocating all the objects to compute a result or provide a service, but has no need for any of the objects (except possibly a few result objects) when the computation is done.
In such cases, region-based memory allocation using an arena is useful. The idea is to allocate a large region of memory called an arena at the beginning of the code segment. The arena is typically a contiguous region, but may be extensible in large chunk sizes. Then all the objects can be allocated very efficiently from the arena. Typically, the objects are just allocated consecutively in the arena. Then at the end of the code segment, all of the allocated objects can be freed with very low overhead by just freeing the arena. Any result object that is intended to be longer-lived and last past the end of the code segment should not be allocated from the arena or should be fully copied before the arena is freed.
Arenas have been found to be useful for a number of common programming patterns, and when applicable, can reduce memory management overhead in non-garbage collected languages. For instance, for a server serving memory-heavy requests, each request is likely independent, so most or all of the objects allocated while serving a particular request can be freed when the request has been fulfilled. Therefore, all the objects allocated during the request can be allocated in an arena, and then freed all at once at the completion of the request.
In a related vein, arenas have been useful for protocol buffer processing, especially when unmarshalling the wire format into the in-memory protocol message object. Unmarshalling a message's wire format to memory can create many large objects, strings, arrays, etc., because of the complexity of messages and the frequent nesting of sub-messages inside other messages. A program may often unmarshal one or more messages, make use of the in-memory objects for a period of time, and then be done with those objects. In this case, all of the objects created while unmarshalling the message(s) can be allocated from an arena and freed all at once. The C++ protocol buffer documentation provides an example of using arenas. Arenas may similarly be useful for other kinds of protocol processing, such as decoding JSON.
We would like to get some of the benefits of arenas in the Go language. In the next section, we propose a design of arenas that fits with the Go language and allows for significant performance benefits, while still ensuring memory safety.
Note that there are many applications where arenas will not be useful, including applications that don't do allocation of large amounts of data, and applications whose allocated objects have widely varying lifetimes that don't fit the arena allocation pattern. Arenas are intended as a targeted optimization for situations where object lifetimes are very clear.
Proposal
We propose the addition of a new
arena
package to the Go standard library. The arena package will allow the allocation of any number of arenas. Objects of arbitrary type can be allocated from the memory of the arena, and an arena automatically grows in size as needed. When all objects in an arena are no longer in use, the arena can be explicitly freed to reclaim its memory efficiently without general garbage collection. We require that the implementation provide safety checks, such that, if an arena free operation is unsafe, the program will be terminated before any incorrect behavior happens.For maximum flexibility, we would like the API to be able to allocate objects and slices of any type, including types that can be generated at run-time via reflection.
We propose the following API:
The application can create an arbitrary number of arenas using
arena.New
, each with a different lifetime. An object with a specified type can be allocated in a particular arena usinga.New
, wherea
is an arena. Similarly, a slice with a specified element type and capacity can be allocated from an arena usinga.NewSlice
. Because the object and slice pointers are passed via an empty interface, any type can be allocated. This includes types that are generated at run-time via thereflect
library, since areflect.Value
can be converted easily to an empty interface.The application explicitly frees an arena and all the objects allocated from the arena using
a.Free
. After this call, the application should not access the arena again or dereference a pointer to any object allocated from this arena. The implementation is required to cause a run-time erro and terminate the Go program if the application accesses any object whose memory has already been freed. The associated error message should indicate that the termination is due to access to an object in a freed arena. In addition, the implementation must cause a panic or terminate the Go program ifa.New
ora.NewSlice
is called aftera.Free
is called.a.New
anda.NewSlice
should also cause a panic if they are called with an argument which is not the correct form (**T
fora.New
and*[]T
fora.NewSlice
).Here is some sample code as an example of arena usage:
There may be an implementation-defined limit, such that if the object or slice requested by calls to
a.New
ora.NewSlice
is too large, the object cannot be allocated from the arena. In this case, the object or slice is allocated from the heap. If there is such an implementation-defined limit, we may want to have a way to expose the limit. We’ve listed it as one of the possible metrics mentioned in the “Open Issues” section. An alternate API would be to not allocate the object or slice if it is too large and instead leave the pointer arguments unchanged. This alternate API seems like it would be more likely to lead to programming mistakes, where the pointer arguments are not properly checked before being accessed or copied elsewhere.For optimization purposes, the implementation is allowed to delay actually freeing an arena or its contents. If this optimization is used, the application is allowed to proceed normally if an object is accessed after the arena containing it is freed, as long as the memory of the object is still available and correct (i.e. there is no chance for incorrect behavior). In this case, the improper usage of
arena.Free
will not be detected, but the application will run correctly, and the improper usage may be detected during a different run.The above four functions are the basic API, and may be sufficient for most cases. There are two other API calls related to strings that are fairly useful. Strings in Go are special, because they are similar to slices, but are read-only and must be initialized with their content as they are created. Therefore, the
NewSlice
call cannot be used for creating strings.NewString
below allocates a string in the arena, initializes it with the contents of a byte slice, and returns the string header.In addition, a common mistake with using arenas in Go is to use a string that was allocated from an arena in some global data structure, such as a cache, which that can lead to a run-time exception when the string is accessed after its arena is freed. This mistake is understandable, because strings are immutable and so often considered separate from memory allocation. To deal with the situation of a string whose allocation method is unknown,
HeapString
makes a copy of a string using heap memory only if the passed-in string (more correctly, its backing array of bytes) is allocated from an arena. If the string is already allocated from the heap, then it is returned unchanged. Therefore, the returned string is always usable for data structures that might outlast the current arenas.Of course, this issue of mistakenly using an object from an arena in a global data structure may happen for other types besides strings, but strings are a very common case for being shared across data structures.
We describe an efficient implementation of this API (with safety checks) in the "Implementation" section. Note that the above arena API may be implemented without actually implementing arenas, but instead just using the standard Go memory allocation primitives. We may implement the API this way for compatibility on some architectures for which a true arena implementation (including safety checks) cannot be implemented efficiently.
Rationale
There are a number of possible alternatives to the above API. We discuss a few alternatives, partly as a way to justify our above choice of API.
Removing Arena Free
One simple adjustment to the above API would be to eliminate the arena
Free
operation. In this case, an arena would be freed automatically only by the garbage collector, once there were no longer any pointers to the arena itself or to any objects contained inside the arena. The big problem with not having aFree
operation is that arenas derive most of their performance benefit from more prompt reuse of memory. Though the allocation of objects in the arena would be slightly faster, memory usage would likely greatly increase, because these large arena objects could not be collected until the next garbage collection after they were no longer in use. This would be especially problematic, since the arenas are large chunks of memory that are often only partially full, hence increasing fragmentation. We did prototype this approach where arenas are not explicitly freed, and were not able to get a noticeable performance benefit for real applications. An explicitFree
operation allows the memory of an arena to be reused almost immediately. In addition, if an application is able to use arenas for almost all of its allocations, then garbage collection may be mostly unneeded and therefore may be delayed for quite a long time.APIs that directly return the allocated objects/slices
An alternate API with similar functionality, but different feel, would replace
(*Arena).New
and(*Arena).NewSlice
with the following:An example of usage would be:
This API potentially seems simpler, since it returns the allocated object or slice directly, rather than requiring that a pointer be passed in to indicate where the result should be stored. This allows convenient use of Go’s idiomatic short variable declaration, but does require type assertions to convert the return value to the correct type. This alternate API specifies the types to be allocated using
reflect.Type
, rather than by passing in an interface value that contains a pointer to the required allocation type. For applications and libraries that already work on many different types and use reflection, specifying the type usingreflect.Type
may be convenient. However, for many applications, it may seem more convenient to just pass in a pointer to the type that is required.There is an efficiency distinction in the
NewSlice
call with the two choices. In theNewSlice
API described in the "Proposal" section, the slice header object is already allocated in the caller, and only the backing element array of the slice needs to be allocated. This may be all that is needed in many cases, and hence more efficient. In the new API in this section, theSlice
call must allocate the slice object as well in order to return it in the interface, which causes extra heap or arena allocation when they are often not needed.Another alternative for
a.New
is to pass in a pointer to type T and return a pointer totype T (both as empty interfaces):
An example use of this API call would be:
intPtr := a.New((*int)(nil)).(*int)
. Although this also allows the use of short variable declarations and doesn’t require the use of reflection, the rest of the usage is fairly clunky.Simple API using type parameterization (generics)
We could have an optional addition to the API that uses type parameterization to express the type to be allocated in a concise and direct way. For example, we could have generic
NewOf
andNewSliceOf
functions:Then we could allocate objects from the arena via code such as:
We don’t think these generic variants of the API can completely replace the suggested methods above, for two reasons. First, the
NewOf
function can only allocate objects whose type is specified at compile-time. So, it cannot satisfy our goal to support allocation of objects whose type is computed at run-time (typically via thereflect
library). Second, generics in Go are just arriving in Go 1.18, so we don’t want to force users to make use of generics before they are ready.Compatibility
Since this API is new, there is no issue with Go compatibility.
Implementation
In order to fit with the Go language, we require that the semantics of arenas in Go be fully safe. However, our proposed API has an explicit arena free operation, which could be used incorrectly. The application may free an arena A while pointers to objects allocated from A are still available, and then sometime later attempt to access an object allocated from A.
Therefore, we require that any implementation of arenas must prevent improper accesses without causing any incorrect behavior or data corruption. Our current implementation of the API gives a memory fault (and terminates the Go program) if an object is ever accessed that has already been freed because of an arena free operation.
Our current implementation performs well and provides memory allocation and GC overhead savings on the Linux amd64 64-bit architecture for a number of large applications. It is not clear if a similar approach can work for 32-bit architectures, where the address space is much more limited.
The basic ideas for the implementation are as follows:
A
uses a distinct range in the 64-bit virtual address spaceA.Free
unmaps the virtual address range for arenaA
A
still exists and is dereferenced, it will get a memory access fault, which will cause the Go program to terminate. Because the implementation knows the address ranges of arenas, it can give an arena-specific error message during the termination.So, we are ensuring safety by always using a new range of addresses for each arena, in order that we can always detect an improper access to an object that was allocated in a now-freed arena.
The actual implementation is slightly different from the ideas above, because arenas grow dynamically if needed. In our implementation, each arena starts as a large-size "chunk", and grows incrementally as needed by the addition of another chunk of the same size. The size of all chunks is chosen specifically to be 64 MB (megabytes) for the current Go runtime on 64-bit architectures, in order to make it possible to recycle heap meta-data efficiently with no memory leaks and to avoid fragmentation.
The address range of these chunks do not need to be contiguous. Therefore, when we said above that each arena A uses a distinct range of addresses, we really meant that each chunk uses a distinct range of addresses.
Each chunk and all the objects that it contains fully participate in GC mark/sweep until the chunk is freed. In particular, as long as a chunk is part of an arena that has not been freed, it is reachable, and the garbage collector will follow all pointers for each object contained in the chunk. Pointers that refer to other objects contained in the chunk will be handled very efficiently, while pointers to objects outside the chunk will be followed and marked normally.
The implementation calls
SetFinalizer(A, f)
on each arena A as it is allocated, wheref
callsA.Free
. This ensures that an arena and the objects allocated from it will eventually be freed if there are no remaining references to the arena. The intent though is that every arena should be explicitly freed before its pointer is dropped.Because unmapping memory is relatively expensive, the implementation may continue to use a chunk for consecutively allocated/freed arenas until it is nearly full. When an arena is freed, all of its chunks that are filled up are immediately freed and unmapped. However, the remaining part of the current unfilled chunk may be used for the next arena that is allocated. This batching improves performance significantly.
Because of the large 64-bit address space, our prototype implementation has not required reusing the virtual addresses for any arena chunks, even for quite large and long-running applications. However, the virtual addresses of most chunks can eventually be reused, since there will almost always be no more reachable pointers to anywhere in the chunk. Since the garbage collector sees all reachable pointers, it can determine when an address range can be reused.
The implementation described above demonstrates that it is possible to implement the Arena API for 64-bit architectures with full safety, while still providing performance benefits. Many other implementations are possible, and some may be tuned for other types of usage. In particular, because of the 64 MB chunk size, the above implementation may not be useful for applications that need to create a large number of arenas that are live at the same time (possibly because of many concurrent threads). It is probably most appropriate that there should only be a few to 10's of arenas in use at any one time. Also, it is not intended that arenas be shared across goroutines. Each arena has a lock to protect against simultaneous allocations by multiple goroutines, but it would be very inefficient to actually use the same arena for multiple goroutines. Of course, that would rarely make sense anyway, since the lifetimes of objects allocated in different goroutines are likely to be quite different.
Open issues
Another possibility in the design space is to implement the API described in the "Proposal" section, but without the safety checks, or with an option to disable the safety checks. The idea here is that the performance savings from the use of arenas can be increased by doing an implementation that doesn't have safety guarantees. As compared to the implementation described above, we can avoid the mapping and unmapping overhead, and reuse the memory of an arena much more quickly (and without OS involvement) when it is freed. We have done a prototype of such an implementation, which we call "unsafe arenas". We have seen an additional 5-10% improvement in performance in some cases when using unsafe arenas rather than our safe arena implementation. However, we feel very strongly that arenas in Go need to be safe. We do not want the use of arenas to lead to memory bugs that may be very hard to detect and debug, and may silently lead to data corruption. We think that it is better to continue to optimize the implementation of safe arenas, rather than trying to support unsafe arenas.
It would be useful to have some run-time metrics associated with arenas. The desired metrics will depend somewhat on the final API, so we have not yet tried to decide the exact metrics that will cover the application needs. However, here are some metrics which might be useful:
Another open issue is whether arenas can be used for allocating the elements of a map. This is
possible, but it is not clear what a good API would be. Also, there might be unusual cases if the arena used for the main map object is different from the arena used to allocate new elements of the map. With generics arriving in Go 1.18, generic maps (or hash tables) can now be implemented in user libraries. So, there could be a user-defined generic map implementation that allows optionally specifying an arena for use in allocating new elements. This might be the best solution, since that would allow for greater flexibility than adjusting the semantics of the built-in
map
type.Protobuf unmarshalling overheads
As noted above, arenas are often quite useful for reducing the allocation and GC overhead associated with the objects that are created as a protobuf message is being unmarshaled. We have prototyped changes to the protobuf package which allow for providing an arena as the allocation option for objects created during unmarshalling. This arrangement makes it quite easy to use arenas to reduce the allocation and GC overhead in applications that make heavy use of protobufs (especially unmarshalling of large protobufs). If the arena proposal is accepted and implemented in Go, then it would make sense to extend the protobuf package to provide such an arena allocation option.
The text was updated successfully, but these errors were encountered: