Search code examples
iosperformancerendercalayer

The fastest way to render huge amount of rectangles in iOS?


I have a lot of small rects, opaque, solid colored, not overlapping, with frequently changing position and size. Rendering them in different ways always produces lags on real devices. I've tried the following methods:

  • render all via CGContext in draw(inRect:) method
  • use individual CAShapeLayer instances for each rect
  • use CALayer instances with pre-rendered content - the best in performance but produces artifacts on borders when rects are scaling
  • UIimageView instances with small pre-generated images

Also tried to adjust various CALayer options (ex. edgeAntialiasingMask, drawsAsynchronously, shouldRasterize...), but still couldn't eliminate lags.

example

So, is there working approach to do that and get no/minimum lags?

Update with measurements and answer

Thanks to @Saurav for the tip in comments, I've found with Time Profiles that UIView.convert(rect: to:) method eats 35% of CPU time, and UIView.setFrame(...) eats another 15%.

Rendering itself doesn't eat significant CPU time when refreshing frames - checked for approaches via draw(inRect:) and pre-rendered UIImageView.


Solution

  • Have you followed these: 1. Avoid creating multiple instances of CALayer or UIView. 2. Create all 1000s of layers or views once inside viewDidLoad and update the frame whenever needed.

    Calculation of frames which you are doing may be blocking the thread.