swift autorelease value-add

Hello,

I am wondering the value-add of autorelease in swift.

Look at this code:

for i in (0...10)
{
   autorelease
   {
      let obj1=MyClass()
      ...
   }
}

obj1 will be released at the end of autorelease block.

But i can also work with a function like this (or a closure):

func test()
{
   let obj1=MyClass()
   ...
}

for i in (0...10)
{
   test()
}

obj1 will be released at the end of the test function.

Do you agree we have the same result in memory in both cases ?

If so, when should we work with autorelease ?

Thanks

In order to answer we need to talk about ARC, which still exists "under the covers", but is managed by the swift compiler.

Some functions return "autoreleased" objects. These are objects with a retain count of 1, but they have been added to an "auto-release pool".

An autorelease pool is a list of objects that should be sent a release "soon", where soon usually means the next time your app services the main event loop.

If you have a function that creates a very large number of autoreleased objects, your app's memory footprint can grow while the app is running. The objects will get released once the function finishes and your app services the event loop, but in the meantime, they take up memory. This is not a memory leak, but it can increase the total memory footprint of your app. (On modern devices you have to create a LOT of large objects in order for this to be an issue. The days of having less than a megabyte of app memory are long gone.)

The autorelease statement creates a local autorelease pool that accumulates objects while the code in braces is executed. Once you leave the scope of the braces, the autorelease pool is "drained". (All the objects get sent a release message, causing them to be deallocated if there are no other strong references to them.)

I believe allocating reference objects like class instances is an example of creating an autoreleased object, so your example of a for loop that creates multiple class objects and stores them in a local example would probably be a case where an autorelease pool would keep your app's memory footprint from growing while the for loop runs.

swift autorelease value-add
 
 
Q