[英]Why using dispatch_async is so slow compared to not using it at all?
我想知道为什么我的代码运行速度比使用dispatch_async要慢得多,而不是我根本不使用它。 我试图通过屏蔽它并使用UIGraphicsImageRenderer来模糊我的UIImage的边缘(不确定它是否是最有效的方式......)但是当我不使用dispatch_async时,它的运行速度要快得多。 这是为什么? 这是我的代码和我从代码中得到的结果。 任何帮助都非常感谢。
self.view.backgroundColor = [UIColor whiteColor];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* Img = [UIImage imageNamed:@"1"];
UIImageView * imageview = [[UIImageView alloc]initWithImage:Img];
UIGraphicsImageRenderer * renderer = [[UIGraphicsImageRenderer alloc] initWithSize:Img.size];
UIBezierPath*path=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(20,20,170,170) cornerRadius:5.0];
path.lineWidth = 20;
CAShapeLayer*shapeLayer = [CAShapeLayer new];
shapeLayer.path=path.CGPath;
[shapeLayer setFillColor:[UIColor redColor].CGColor];
[shapeLayer fillColor];
UIImage *shapeImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull context){
[shapeLayer renderInContext: context.CGContext];}];
CIImage * shapeCimage = [[CIImage alloc] initWithImage:shapeImage];
CIFilter * gaussianBlurFilter = [CIFilter filterWithName: @"CIGaussianBlur"];
[gaussianBlurFilter setValue:shapeCimage forKey: @"inputImage"];
[gaussianBlurFilter setValue:@15 forKey:@"inputRadius"];
CIImage * blurredCIImage = [gaussianBlurFilter valueForKey:kCIOutputImageKey];
UIImage * blurredImage = [UIImage imageWithCIImage:blurredCIImage];
UIImageView *maskedImageView = [[UIImageView alloc]initWithImage:blurredImage];
maskedImageView.contentMode = UIViewContentModeScaleAspectFit;
maskedImageView.frame = imageview.frame;
imageview.layer.mask=maskedImageView.layer;
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:imageview];
});
});
应该在主队列上执行所有UI内容。 如果没有,这可能会导致错误(不时)和令人难以置信的缓慢性能。
这是因为UIApplication
在主线程上设置了。
您可以查看本教程:
最好的祝福
GCD管理具有不同优先级的队列。 优先级越高,该队列中的作业获得的CPU时间百分比越大。
Apple设计了他们的优先级系统,以便用户交互(主线程)获得最高优先级,以保持UI响应。 DISPATCH_QUEUE_PRIORITY_DEFAULT的优先级低于主线程,因此使用该优先级提交的作业在主线程上运行的时间将超过一次。 你可以尝试使用DISPATCH_QUEUE_PRIORITY_HIGH作为实验,你不应该在生产应用程序中这样做,因为它会减慢用户界面(Apple可能拒绝你的应用程序。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.