Skip to content

Instantly share code, notes, and snippets.

@an0
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an0/b4b6ca8d2d1c00c93a64 to your computer and use it in GitHub Desktop.
Save an0/b4b6ca8d2d1c00c93a64 to your computer and use it in GitHub Desktop.
Is Arrays Building with Reduce Optimizable?

Context:

  1. https://twitter.com/an0/status/627476411050147840
  2. http://airspeedvelocity.net/2015/08/03/arrays-linked-lists-and-performance/

Array concatenation optimization is easy. The hard part is ARC optimization. Essentially, the question is whether ARC can eliminate the autorelease_1 & retain_1 pair and just transfer the ownership from obj to arg:

// I have to use Objective-C code to demonstrate because there is no Manual Reference Counting in Swift at all.
    
Obj *foo(Obj *arg) {
    Obj *result = [arg retain_1];
    …
    return [result autorelease_2];
}
​
{
    …
    Obj *obj = …;
    obj = [foo([obj autorelease_1]) retain_2];
    …
}

ARC surely does eliminate the autorelease_2 & retain_2 pair. That’s exactly what objc_retainAutoreleaseReturnValue and objc_retainAutoreleasedReturnValue do.

I had the impression that the similar optimization is also done for autorelease_1 & retain_1. But I didn’t found any supporting documentation. Since ARC is open sourced there must be people who can confirm whether it is true or false.

If ARC doesn’t do this optimization yet I still think it is doable in future because we programmers can clearly see the optimization opportunity here and compilers are always evolving to do what we can do with code and then better us.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment