0

I have a LazyVStack in a scrollView with many images. The size of the images in the scrollView is quite small, about 300x300 points. The images are extracted from Data stored in CoreData. The average image size is 1024x1024 and 500KB.

At the moment I am just loading the images without any caching or resizing using the something similar to the following:

var items: [Item]

var body: some View {
    GeometryReader { geometry in
        ScrollViewReader { scrollView in
            ScrollView(.vertical) {
                LazyVStack {
                    ForEach(items, id: \.id) { item in
                        Image(uiImage: UIImage(data: item.imageData!) ?? UIImage())
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 300, height: 300)
                    }
                }
            }
        }
    }
}

What I'm wondering is what is the best practice for this scenario. Am I needlessly slowing down my scroll by having the images resized? The original image sizes are 1024x1024 and about 500kb.

I have thought of creating another field in CoreData for thumbnail and resizing when I store there but that will use additional storage and I would like to avoid that if not necessary.

alionthego
  • 8,508
  • 9
  • 52
  • 125
  • 1
    *The original image sizes are 1024x1024 and about 500kb.* - I'd think about thumbnails. – Asperi Jan 11 '22 at 14:50
  • 1
    A big hit is creating the `UIImage` inside the view `body`, and not ran in `onAppear` and saved to a `@State` variable. Same goes with `init` and `body`, try avoid creating `UIImage`s. When you create these images, before you set them to a `@State` variable - as Asperi suggests, you could also create the thumbnails here. – George Jan 11 '22 at 21:21
  • Thanks @Asperi I've added thumbnails and can see an improvement. – alionthego Jan 11 '22 at 23:27
  • @George I've looked at adding a dictionary in the viewModel to store the UIImage's but it does add quite a bit of overhead, especially as this is a dynamic app with coreData objects being constantly added. I'm wondering if this is a standard practice and necessary for improved performance? The above example was for simplicity. My app is a chat app and keeping track of messages with images and keeping their UIImage in a separate array somewhere will get a bit messy. – alionthego Jan 11 '22 at 23:30
  • I can see your point about the creation of the UIImage each time but my understanding was under the hood it actually creates the buffer once and keeps it around in temporary memory so it actually wouldn't be doing that work constantly. My understanding of that process though is very limited. It was based on this WWDC video: https://developer.apple.com/videos/play/wwdc2018/219 – alionthego Jan 11 '22 at 23:34

0 Answers0