I have been working on an object class for my iPhone app that lazy loads images when they are first requested by another part of the app. I decided to make the loading of the image thread safe so the same image doesn’t get loaded twice by accident, however I am curious about the overhead of making an @synchronized(self) call every time the accessor is run, like so:
- (UIImage *)image
{
@synchronized(self)
{
if (_image == nil)
{
_image = [UIImage imageWithContentsOfFile:self.imageUrl];
}
}
return _image;
}
Would it be better to first check if the property is nil and then use the @synchronized directive?
- (UIImage *)image
{
if (_image == nil)
{
@synchronized(self)
{
if (_image == nil)
{
_image = [UIImage imageWithContentsOfFile:self.imageUrl];
}
}
}
return _image;
}
Any thoughts?
The overhead is minimal, but the ovhead of loading an image may be huge and, thus, that you surround it with a synchronization primitive means that anything blocking on that could pay the price….