This question already has an answer here:
It is said that nonatomic
option will make your setter method run faster. I googled it but am not able to understand. Could someone tell me why?
This question already has an answer here:
It is said that nonatomic
option will make your setter method run faster. I googled it but am not able to understand. Could someone tell me why?
Declaring a property atomic
makes compiler generate additional code that prevents concurrent access to the property. This additional code locks a semaphore, then gets or sets the property, and then unlock the semaphore. Compared to setting or getting a primitive value or a pointer, locking and unlocking a semaphore is expensive (although it is usually negligible if you consider the overall flow of your app).
Since most of your classes under iOS, especially the ones related to UI, will be used in a single-threaded environment, it is safe to drop atomic
(i.e. write nonatomic
, because properties are atomic
by default): even though the operation is relatively inexpensive, you do not want to pay for things that you do not need.
see the difference between atomic and nonatomic in objective c
Atomic
Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.
An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. The trade-off is that these properties will be a little slower to access than a nonatomic equivalent.
Non-Atomic
Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.
@property (strong) NSString *str;
Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.
setter & getter for these Atomic property
An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. these properties will be a little slower to access than a nonatomic equivalent.
@property (strong,nonatomic) NSString *str;
Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.
setter & getter for these Nonatomic property
-(NSString *) str{ return str; }} -(void) setStr: (NSString *) newString{ str = newString; }
So by looking on the setter & getter methods for both Atomic & nonatomic that nonatomic methods are very light weight.