[fpc-pascal] For ..in GetEnumerator Allocation

Michael Van Canneyt michael at freepascal.org
Wed Oct 4 17:03:30 CEST 2017

On Wed, 4 Oct 2017, Ryan Joseph wrote:

>> On Oct 4, 2017, at 4:26 PM, Michael Van Canneyt <michael at freepascal.org> wrote:
>> You can do so by overriding the newinstance and it's sister method of
>> your enumerator class.
> Can you explain how this works or give an example? Not sure how these gets around the problem of alloc/dealloc for each iterator.

Careful, the iterator is instantiated only once per loop ?

Newinstance allocates the memory for a new instance of the class.
By default this is GetMem(instanceSize).

What you can do is allocate somewhere a block of the correct size, 
once, and always return this single block.

Of course, you need to know for sure that only 1 instance of your enumerator
will be active at any given point in your program. 
If there are multiple, you could allocate a static array and allocate from that.

The FreeInstance procedure does a freemem, by default, but you can change
that to do nothing. (in case of an array, you mark the element unused)


More information about the fpc-pascal mailing list