Reputation: 1215
I wanted to know why my code runs much slower when I use dispatch_async compared to when I don't use it at all. I'm trying to blur the edges of my UIImage by masking it and using UIGraphicsImageRenderer (Not sure if it's the most efficient way or not..)But when I don't use dispatch_async, It runs much much faster. Why is that? Here is my code and the result I get from my code. Any help is muchhhhh appreciated.
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];
});
});
Upvotes: 4
Views: 1247
Reputation: 131491
GCD manages queues with different priorities. The higher the priority, the larger the percentage of the CPUs' time the jobs in that queue get.
Apple designed their priority system so that user interaction (the main thread) gets the highest priority, in order to keep the UI responsive. DISPATCH_QUEUE_PRIORITY_DEFAULT is a lower priority than the main thread, so a job submitted with that priority will take longer than one run on the main thread. You could try using DISPATCH_QUEUE_PRIORITY_HIGH as an experiment, you shouldn't do that in a production app because it will slow down the UI (and Apple may reject your app.)
Upvotes: 3
Reputation: 861
All UI stuff should be performed on the main queue. If not, this could lead to bugs (from time to time) and incredibly slow performance.
The reason for this is because UIApplication
gets set up on the main thread.
You can check this tutorial out:
best regards
Upvotes: 3