Auto Release Pool Question

Another dumb question from a newbie.

If I create a brand new console application C# project for macOS (either Toffee or Island backend), I get this boiler plate:

    static class Program
    {
        public static Int32 Main(string[] args)
        {
            using (__autoreleasepool)
            {
                printf("The magic happens here.");
                return 0;
            }
        }
    }

I’ve read the docs on garbage collection and automatic reference counting.

Am I right in thinking that I shouldn’t have to create anymore of these autoreleasepools and that this one has been created simply because it encloses a long running loop (i.e. the main application loop). I got spooked as when I created a new Swift console application I don’t see any references to memory management - only with C# on macOS.

Correct.

the only times you’d want to man rally create auto-release pools (ARP) in your own code is if you have something long-running (or infinitely running) that is going to allocate significant memory.

for example if you have something like

while (appNotTerminated)
{
  // waits for something to happen & does things with it
}

by default this code would keep adding stuff to the ARP that was a created by the surrounding context of the OS that called into your code. that ARP would keep growing and never flush, because tis code never returns. So you might need to do a

while (appNotTerminated)
{
  // waits for something to happen 
  using (__autoreleasepool) {
    // & does things with it
  }
}

Similarly, of you insatiate your own threads using low-level APIs (notes ay GCD), you might need to create your own ARPs there. Not something usually done in Cocoa code.

This would only be necessary for Cocoa-style objects yes — using the standard Cocoa platform, or explicitly using Cocoa/Objective-C objects when using Island/Darwin (which is a more advanced topic, see https://docs.elementscompiler.com/Compiler/BackEnds/Island/ToffeeV2/. A regular Cocoa project for now will always use our standard/classic Cocoa support (the “Toffee”) compiler backend).

All other platforms, including Island, use GC and don’t rely own ARPs.

Very clear explanation - thank you.

1 Like