Objective-C Copy vs Strong

I was recently working on putting together iOS code review guidelines with my colleagues at work. One of the guidelines I had proposed was  –  “Use copy instead of strong when declaring properties of objects, which have mutable variants e.g. NSString, NSArray, etc”. A colleague expressed concerns that using copy would be a hit on the performance.

In my view, one of the main reasons to use copy attribute was to preserve encapsulation. But, I was curious about the performance concerns myself. All I remembered was reading that Apple optimizes the copy attribute for you but had no data. I put together a sample program and here are some of the results:

1. An array of strings, size 1,000,000

Attribute Time (nano seconds)
Copy 25
Strong 23

2. An array of string, size 1,000,000,000

Attribute Time (nano seconds)
Copy 25
Strong 22

The above results fluctuated some times but the difference between copying and retaining  an array with a billion objects was steadily ~3 nano seconds. It is very rare for us to have such big arrays in our application, and, I am not so sure whether I would want to gain 2 nano seconds at the cost of ending up with hard to debug issues.

Here is the program I created to do this simple test (with some comments included).

You can find a good description of dispatch_benchmark here. Additional details of why to use copy over strong can be found here.