On Sunday, October 1, 2023 11:13:43 AM MDT dhs via Digitalmars-d-learn wrote: > On Sunday, 1 October 2023 at 13:27:37 UTC, Adam D Ruppe wrote: > > On Sunday, 1 October 2023 at 09:01:53 UTC, dhs wrote: > >> When D creates a dynamic array, it returns a slice. Functions > >> that add or remove elements begin by asking the memory manager > >> for the dynamic array that the slice belongs to. Only then can > >> they go on and add elements. > > > > Why is this a problem? It is convenient and usually works fine. > > > > I use the built in arrays very very often for a lot of things. > > It may not be a problem in practice. My concern was performance, > because each time we add an element to the array, the garbage > collector has to map the slice to the allocation it belongs to.
In general, this is a non-issue. Usually, the only time that you might need to worry about it is when you're building an array with a bunch of elements, in which case, std.array.Appender gives you a wrapper which avoids a lot of that overhead (since it keeps track of the capacity separately): https://dlang.org/phobos/std_array.html#appender However, most code ends up using arrays without appending, and appending to an array here and there doesn't really impact performance. In addition, because D's dynamic arrays are slices of memory rather than owning their memory, passing them around is extremely cheap in comparison to std::vector. You're basically just passing around DynamicArray(T) { size_t length; T* ptr; } so you don't end up with a bunch of unnecessary copies, whereas in C++, you have to be careful about passing by reference or const reference (or worrying about move constructors) in order to avoid copying when you don't actually want a copy. So, unless you're doing a _lot_ of appending to dynamic arrays in D, and you're doing it a lot outside of when a dynamic array is first created, the way that D's arrays work will easily beat out how std::vector works in terms of performance. Of course, the exact performance characteristics are going to depend on what you're doing in your program, and whether the approach of D's dynamic arrays or C++'s std::vector is better depends on what your code is doing, but for most code, D's approach works extremely well. It just tends to take some getting used to, because the way that D's arrays work work is kind of unique. - Jonathan M Davis