On Wednesday, 3 August 2016 at 05:44:42 UTC, ag0aep6g wrote:
On 08/02/2016 11:48 PM, Mark Twain wrote:
global ImmutableArray!int Data;


MutableArray!int DataCopy = Data.Copy; // Creates a mutable copy of Data.
... Do work with DataCopy ...
Data.Replace(DataCopy); // Makes a copy of DataCopy.

What benefit do ImmutableArray and MutableArray have over built-in arrays? The thing above can be done with built-in arrays:

----
immutable(int)[] Data;
int[] DataCopy = Data.dup; // Creates a mutable copy of Data.
... Do work with DataCopy ...
Data = DataCopy.idup; // Makes a copy of DataCopy.
----


The built in array is mutable and exposes the same interface for the immutable copy. The only difference is that the immutable copy is marked immutable.

My method changes the interface. An "immutable" type has an immutable interface while a mutable type has a mutable interface.

For simple types, and value types, there is obviously no advantage... their interfaces are essentially empty/DNE.

[...]
void foo()
{
    MutableArray!int Data;
    scope(Exit) Data.Reuse();
}

Reuse can simply mark the memory reusable rather then freeing it. This memory can then be reused the next time foo is called(or possibly use
the stack for memory).

As far as I see, "marking for reuse" is practically the same as freeing here. If Data were static, there could be a difference.

For built-in arrays, you can mark an array for reuse by setting the length to 0 and calling assumeSafeAppend, like so:

No again. Data in the example above is a local variable that allocates memory that would generally be free'ed at the end of the function call. Hence every call to foo results in a malloc/free pair for Data. By reusing the memory, if possible, one can potentially skip the malloc/free. Therefore instead of potentially thrashing the memory pool, after a few runs of foo, Data would generally not allocate.

When one has hundreds of functions allocating and deallocating memory, this is a big deal. This is effectively caching or similar memory pooling.

Your assumeSafeAppend works while the object is in existence. This thing works between the existence of the object.


Reply via email to