0

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?

kmell96
  • 1,365
  • 1
  • 15
  • 39

2 Answers2

2

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. You can read more about caching here https://stackoverflow.com/a/8644628/4757335.

Community
  • 1
  • 1
Misternewb
  • 1,066
  • 9
  • 12
0

The first method would basically call the alloc twice where the second one would only call alloc once on the image. Therefore, the first method would use a larger amount of memory.

Ruchira Randana
  • 4,021
  • 1
  • 27
  • 24