开发者

How much overhead is associated with @synchronized(self)?

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....


First off, UIKit is not thread safe, so you need to be careful here. Secondly, UIImage does some caching on it's own so if all you are doing is loading from disk, then just use UIImage imageNamed:.

But, I'm guessing that you might be loading the image from the network, in which case you could use performSelectorOnMainThread:. However, if you are just implementing a straightforward downloading with NSURLConnection, all of the work is done within the main run loop, so you shouldn't need to multi-thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜