简体   繁体   English

Swift是UIImage类的实习生

[英]Swift Is UIImage Class Interning

Should be a simple answer, but I can't find it anywhere. 应该是一个简单的答案,但我在任何地方都找不到。

Suppose I run the following code: 假设我运行以下代码:

let imageView1 = UIImageView(image: UIImage(named: "image3"))
let imageView2 = UIImageView(image: UIImage(named: "image3"))

And then I run this code: 然后运行以下代码:

var image = UIImage(named: "image3")
let imageView1 = UIImageView(image: image)
let imageView2 = UIImageView(image: image)
image = nil

Will both options use the same amount of memory, or would the second option use half as much as the first? 这两个选项使用的内存量是否相同,或者第二个选项使用的内存是第一个选项的一半?

Second approach is preferred, because you create image only once. 首选第二种方法,因为您只创建一次图像。 Also UIImage.init?(named name: String) uses caching, so your image will not be loaded twice in first approach. UIImage.init?(named name: String)使用缓存,因此在第一种方法中不会两次加载图像。 You can read more about caching here https://stackoverflow.com/a/8644628/4757335 . 您可以在这里阅读有关缓存的更多信息https://stackoverflow.com/a/8644628/4757335

The first method would basically call the alloc twice where the second one would only call alloc once on the image. 第一种方法将基本上调用alloc两次,其中,第二个将只调用alloc在图像上一次。 Therefore, the first method would use a larger amount of memory. 因此,第一种方法将使用大量的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM