@@ -78,12 +78,7 @@ - (void)startPrefetchingAtIndex:(NSUInteger)index {
7878 didPrefetchURL: self .prefetchURLs[index]
7979 finishedCount: self .finishedCount
8080 totalCount: self .prefetchURLs.count
81- ];
82- }
83- if (self.prefetchURLs .count > self.requestedCount ) {
84- dispatch_async (self.prefetcherQueue , ^{
85- [self startPrefetchingAtIndex: self .requestedCount];
86- });
81+ ];
8782 }
8883 else if (self.finishedCount == self.requestedCount ) {
8984 [self reportStatus ];
@@ -102,7 +97,7 @@ - (void)reportStatus {
10297 [self .delegate imagePrefetcher: self
10398 didFinishWithTotalCount: (total - self .skippedCount)
10499 skippedCount: self .skippedCount
105- ];
100+ ];
106101 }
107102}
108103
@@ -117,14 +112,29 @@ - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock
117112 self.completionBlock = completionBlock;
118113 self.progressBlock = progressBlock;
119114
120- if (urls.count == 0 ){
121- if (completionBlock){
115+ __weak SDWebImagePrefetcher *weakSelf = self;
116+
117+ if (urls.count == 0 ) {
118+ if (completionBlock) {
122119 completionBlock (0 ,0 );
123120 }
124- }else {
125- // Starts prefetching from the very first image on the list with the max allowed concurrency
126- NSUInteger listCount = self.prefetchURLs .count ;
127- for (NSUInteger i = 0 ; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) {
121+ } else {
122+ // http://oleb.net/blog/2013/07/parallelize-for-loops-gcd-dispatch_apply/
123+ // Optimize the maxConcurrentdownloads for effeciency. Since caching operations are involved that are non-trivial using
124+ // dispatch_apply might be helpful.
125+
126+ NSInteger maxNumberOfImages = self.prefetchURLs .count ;
127+
128+ dispatch_apply (maxNumberOfImages/self.maxConcurrentDownloads , dispatch_get_global_queue (self.prefetcherQueue , 0 ), ^(size_t index) {
129+ size_t i = index * self.maxConcurrentDownloads ;
130+ size_t stop = i + self.maxConcurrentDownloads ;
131+ do {
132+ [weakSelf startPrefetchingAtIndex: i++];
133+ } while (i < stop);
134+ });
135+
136+ // Download remaining images.
137+ for (size_t i = maxNumberOfImages - (maxNumberOfImages % self.maxConcurrentDownloads ); i < (size_t )maxNumberOfImages; i++) {
128138 [self startPrefetchingAtIndex: i];
129139 }
130140 }
0 commit comments