2

I have a simple command line tool in swift, which is doing image operations, but the memory is never released. I have extracted the code to repro the issue. The following code is simply loading 50 times a tif image and uncompresses it, and I assume that Swift should release my variables at the end of each loop, however it doesn't and eventually takes more than 4 GB in memory:

    let imageUrlPath = "folder/file.tif"
    for _ in 0...50
    {
        let sourceImg = NSImage(byReferencingFile: imageUrlPath)
        let sourceBitmapRep = NSBitmapImageRep(cgImage: sourceImg!.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
        let sourceImageData = sourceBitmapRep.representation(using: .tiff, properties: [:])
    }
    RunLoop.main.run()  // Total memory taken is 4.3 GB

How can I force memory release ?

Laurent Crivello
  • 3,809
  • 6
  • 45
  • 89
  • 2
    Did you try it with an explicit `autoreleasepool`? Compare https://stackoverflow.com/q/25860942/1187415. – Martin R Jul 04 '21 at 14:40
  • It's indeed better with an autorelease pool, but dedreasing "only" from 4.3 GB to 1.41 GB. getting there but not perfect yet ! – Laurent Crivello Jul 04 '21 at 15:09
  • Try putting `autorelease` outside of the loop, instead of inside – aheze Jul 04 '21 at 15:39
  • I tried too, same issue (1.4GB, already better than 4.3, but still problematic when my loop is not to 50, but thousands. – Laurent Crivello Jul 04 '21 at 15:59
  • 2
    I can't reproduce this once I've added the required `autoreleasepool{}` inside the loop. How large is your TIF file? You should expect some memory growth due to how memory is allocated by the OS, but it should be stable and not grow. Loading a 145k TIF file I see a total memory use of 33MB for any number of images (tested from 500 to 50k). This is compared to a base level of 28MB for 0 loads. The extra 5MB represents the extra memory requested for this operation. If you ask for memory and then free it, it won't be immediately returned to the OS. That's normal and by design. – Rob Napier Jul 04 '21 at 16:55
  • My tif is 22MB (3600 x 3600 16 bits). Do you have the chance to test with such a big file, I have put it here for reference: http://www.petits-suisses.ch/image.tif. Thanks – Laurent Crivello Jul 04 '21 at 18:37

0 Answers0