等待20秒: [NSThread sleepForTimeInterval:20];
问:
用这两个下载图片,为什么明显能感觉到dispatch慢,代码那里有问题吗?
{ [activity startAnimating]; //启动线程 // [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:ImageURL]; dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(newThread, ^{ [self downloadImage:ImageURL]; }); } //线程函数 - (void) downloadImage:(NSString*)url{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSURL *imageUrl = [[NSURL alloc] initWithString:ImageURL]; NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageUrl]; [imageUrl release]; UIImage *bkImage = [[UIImage alloc] initWithData:imageData]; [imageData release]; self.downloadImage.image = bkImage; [bkImage release]; [activity stopAnimating]; [pool release]; }
答:
这个用法确实有问题。
1、你使用global队列可能会导致分派时间过长。由于global队列中可能会含有较多的系统队列。
2、dispatch_async调度本身是有开销的,因此你把[activity startAnimating];放在最上面是不妥的。最好的方式是用一个标志,等待download这个函数所处的核被激活后调。
3、NSThread的方式或许能做更快的切换,因为ARMv6或更高版本的处理器都提供了非常强大的线程切换机制。但是NSThread不会采取多核的分派,因为这个系统接口首先要保证的是用户线程的可靠性。
而Grand Central Dispatch显式地利用分派队列来做多核分派调度,因此如果是在多核处理器上的话用G_C_D更快。
如果你的处理器是单核心的话,那么可以使用切换更快的NSThread。