19

Just a quick question if I may, I have always (since learning obj-c) written int properties as follows...

@property(nonatomic, assign) int myValue;

I am now thinking that this might be overkill and I might as well write...

@property int myValue;

Just curious, I know that "assign" is the default behaviour and that "nonatomic" can be fractionally faster ...

all the best

Gary

3 Answers 3

37
@property(nonatomic, assign) int myValue;

is not the same as

@property int myValue;

The default for a property is atomic (there's no explicit keyword atomic). So the second example is an atomic property. For a property of primitive type I don't know if any locking occurs, but probably a memory write barrier will be introduced (i.e. the setter will force the value to be written back to main memory, instead of just to the cache). Thus atomic properties are considerably slower than nonatomic properties. However, as a fraction of the total execution time of the program, they could still represent a very small percentage. You won't know until you profile your code.

1
  • There is an explicit keyword called atomic (maybe it was introduced since you wrote this?). Oct 3, 2018 at 16:30
8

Well, the question of declaring atomicity is a separate one from whether you explicitly declare attributes that are the default. The former will depend on the nature of your code -- is there likely to be contentious multithread access to the property?

Regarding the latter, it's mostly a matter of style, but in general I think you should err on the side of explicit clarity. Exactly how many seconds of your life does it cost to type those extra few keystrokes?

2

Nonatomic generates less code and is slightly faster. I do agree it's very verbose though.

If your app may use several threads, you'll be glad to have put those explicit qualifiers when you encounter weird bugs...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.