How expensive is alloc'ing and init'ing a small UIImage
I have some code that displays a checkmark as the auxiliary view of a custom subclass UITableViewCell. Currently, I'm implementing this by having a method for my custom subclass that, when called, alloc's a new UIImageView from a new UIImage, which in turn is loaded from a 4K .png file. There's another custom method that removes the view and deallocates it when I want the checkmark to go away.
Obviously this is not the most efficient way to implement this, si开发者_运维知识库nce every time I want to change state I have to alloc and init a new UIImage + associated objects. That being said, the code does work now, and I'm not sure whether it's actually worth it to go and change it to more efficient implementation. Turning the checkbox on or off is a UI thing, so it's never going to happen faster than a human can physically press the screen on their iOS device, and the image it's loading is, like I said, a 4K .png. So, while I know I'm doing this in a really inefficient way, is it inefficient enough that it's worth changing? (I'm not noticing any slowness that would affect the user experience as it is, although the app isn't fully built yet).
The prima facie observation is if the user experience isn't affected then what you have is definitely efficient enough. Premature optimisation is always to be avoided.
That being said, [UImage +imageNamed:]
has an internal cache. Multiple calls to it will usually return the same UIImage object, exactly to help in cases like yours. If possible, use that method to fetch your UIImages.
UIImage
also lazy loads. It's relative cheap to create one, linking it to a particular file, as the work of loading and decoding the file won't be done until someone actually tries to draw the thing. That makes it hard to come up with an empirical idea of speed, since the work you're ordering doesn't occur until a hard-to-predict time in the future.
So it's hard to give an exact answer, and unlikely to be a problem but if you stick to +imageNamed
then you can at least be secure that the OS is doing what it can to help you out.
If you aren't seeing any performance problems as it stands, I'd leave it. It wouldn't surprise me if the OS or filesystem is already caching the file after the first read.
精彩评论