imageNamed vs imageWithContentsOfFile of UIImage class.

多分、少しObjective-cに精通した方ならご存知かと思うのですが[UIImage imageNamed:]のリファレンスには以下の様に書かれております。


This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method locates and loads the image data from disk or asset catelog, and then returns the resulting object.

UIImage Class Reference

要するに、

このメソッドは内部的に呼ばれたイメージをキャッシュから取得します。
キャッシュがなければキャッシュをして返します。

みたいな事です。

昔に比べれば今や端末のメモリ量は1GBを超える端末も出て来ましたが出来れば使用メモリは抑えられるに越した事はないですよね。
そんなこんなで他のメソッドを探してみると、代替メソッドはこの辺でしょうか。

[UIImage imageWithContentsOfFile:]

でも、以前にimageWithContentsOfFileはimageNamedに比べて低速だと言う話を聴いた事がありました。
確かに普通に考えてみればキャッシュされたものを呼び出すんだからそりゃその方が早いとも考えられます。

どれくらい早いのか検証してみました。

検証端末

MacBookAir 13インチ
OS X 10.9.4
1.3GHz Intel Core i5
メモリ 8GB

検証コード

NSDate *date = [NSDate date];
for(NSUInteger i=0; i<100000; i++) {
    UIImage *image = [UIImage imageNamed:EXISTS_IMAGE_NAME];
}
NSLog(@"time is %lf", [date timeIntervalSinceNow] * -1);

※imageWithContentsOfFileは上記のimageNamedの行を

UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:EXISTS_IMAGE_NAME ofType:@"png"]];

と変更します。
※Images.xcassets
※下記の結果はテストを5回した平均値を取っています。

結果は以下
【imageNamed:】

ループ100回
0.00479(s)

ループ1000回
0.02793(s)

ループ10000回
0.25365(s)

ループ100000回
2.3720(s)

【imageWithContentsOfFile:】

ループ100回
0.00040(s)

ループ1000回
0.00301(s)

ループ10000回
0.03266(s)

ループ100000回
0.31092(s)

え!?
imageWithContentsOfFile:の方が早いの!?

これからはimageWithContentsOfFileを使うと言う方向で良いのでしょうか。

ご意見お待ちしております。

コメント

タイトルとURLをコピーしました