Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Managing Memory

This question was cleaned up and the important info moved to the answer below.


I have some questions about memory management.

I am building a photo editing app. So keeping memory usage low is important. Also I am not going to post code because I do not have a big memory leak when doing one specific thing. I just lose a couple of KB's/MB's with everything that happens. And going over tens of thousands of lines of code to find kilobytes is no fun ;)

my app uses core data, lots of cifilter stuff, location, and the basics.

My first view is just a tableview which costs me about 5mb of memory. Then you take some photos, apply some filters, this gets saved to core data and then you go back to that first view.

Is it possible to truly get rid of everything in memory except for the data needed to drive that first view. (that very save and awesome 5mb)

Or will there always be something left behind, even if you set everything to nil?


Bonus Question: is there a difference in file size / cpu load between UIImageJPEGRepresentation and UIImagePNGRepresentation? I know you can set a compression quality with the JPEG method (harder on the cpu/gpu?).

Just trying to reduce memory pressure by all means possible.


Update:

It was pointed out to me that the question might be too vague.

The problems I was having at some point or another were the following:

  • At some points peak memory usage is too high
  • Navigating to a second viewcontroller and back causes a leak
  • Editing an image causes a memory leak.
  • Applying a filter to more than 4-5 images causes a crash because of low memory, there were no more memory leaks at this point. (verified in instruments)

P.s this was all tested on an iPhone 4s , not the simulator.

There was a meme here to lighten the mood on this site a bit.

like image 986
R Menke Avatar asked Jan 15 '15 06:01

R Menke


People also ask

How do you manage memory in Swift?

In Swift, memory management is handled by Automatic Reference Counting (ARC). Whenever you create a new instance of a class ARC allocates a chunk of memory to store information about the type of instance and values of stored properties of that instance.

What is ARC in Swift memory management?

Swift uses Automatic Reference Counting (ARC) to track and manage your app's memory usage. In most cases, this means that memory management “just works” in Swift, and you don't need to think about memory management yourself.

What is memory management in iOS?

Memory management is the programming discipline of managing the life cycles of objects and freeing them when they are no longer needed. Managing object memory is a matter of performance; if an application doesn't free unneeded objects, its memory footprint grows and performance suffers.

What kind of memory allocations takes place in Swift?

There are two ways in which memory is managed in Swift for value and reference types: stack allocation and heap allocation.


2 Answers

This question has been open long enough and I now feel confident enough to answer it.


Different Levels of MM:

Hardware Memory

In Swift with ARC we have no way to clean up the actual hardware ram. We can only make it possible for the OS to do that for us. One part is using the right code (optionals and weak) the other part is creating time for the OS to do it's job.

Imagine we have a function that runs on all threads indefinitely. It does one thing, load an image, convert to black/white and save. All images max at a couple of mb’s and the function creates no Software Memory Leaks. Because images don’t have a set size and might have different compression they don’t have the same footprint. This function will always crash your app.

This “Hardware” Memory Leak is caused by the function always taking the next available slot of memory.

The OS does not step in to “actually clean the memory” because there is no idle time. Putting a delay between each pass completely fixes this.


Language specific MM

Casting

Some operations don’t have an impact on memory, others do:

let myInt : Int = 1
Float(myInt) // this creates a new instance

Try casting instead:

(myInt as Float) // this will not create a new instance.

Reference Types vs Value Types | Classes vs Structs

Both have their advantages and their dangers.

Structs are memory intensive because they are Value Types. This means they copy their values when assigned to another instance, effectively doubling memory usage. There is no fix / work around for this. It is what makes Structs Structs.

Classes don’t have this behaviour because they are Reference Types. They don’t copy when assigned. Instead they create another reference to the same object. ARC or Automatic Reference Counting is what keeps track of these references. Every Object has a reference counter. Each time you assign it, it goes up by one. Each time you set a reference to nil, the enclosing function ends, or the enclosing Object deinits, the counter goes down.

When the counter hits 0 the object is deinitialised.

There is a way to prevent an instance from deinitialising, and thus creating a leak. This is called a Strong Reference Cycle.

Good explanation of Weak

class MyClass {

    var otherClass : MyOtherClass?

    deinit {
        print("deinit") // never gets called
    }
}

class MyOtherClass {

    var myclass : MyClass?

    deinit {
        print("deinit") // never gets called
    }
}

var classA : MyClass? = MyClass()

// sorry about the force unwrapping, don't do it like this
classA!.otherClass = MyOtherClass()
classA!.otherClass!.myclass = classA // this looks silly but in some form this happens a lot

classA = nil
// neither the MyClass nor the MyOtherClass deinitialised and we no longer have a reference we can acces. Immortalitiy reached they have.

set one reference to weak

class MyOtherClass {

    weak var myclass : MyClass?

    deinit {
        print("deinit") // gets called
    }
}

inout

Functions capture the values passed to them. But it is also possible to mark those values as inout. This allows you to change a Struct passed to a function without copying the Struct. This might save memory, depending on what you pass and what you do in the function.

It is also a nice way of having multiple return values without using tuples.

var myInt : Int = 0

// return with inout
func inoutTest(inout number: Int) {

    number += 5

}

inoutTest(&myInt)
print(myInt) // prints 5

// basic function with return creates a new instance which takes up it's own memory space
func addTest(number:Int) -> Int {

    return number + 5

}

Functional Programming

State is Value over Time

Functional programming is the counter part of Object Oriented programming. Functional programming uses Immutable state.

More on this here

Object Oriented programming uses Objects that have changing/mutating states. Instead of creating a new value, the old values are updated.

Functional Programming can use more memory.

example on FP


Optionals

Optionals allow you to set thing to nil. This will lower the reference count of Classes or deinitialise Structs. Setting things to nil is the easiest way to clean up memory. This goes hand in hand with ARC. Once you have set all references of a Class to nil it will deinit and free up memory.

If you don’t create an instance as an optional, the data will remain in memory until the enclosing function ends or the enclosing class deinits. You might not know when this will happen. Optionals give you control over what stays alive for how long.


API MM

Many "memory leaks" are cause by Frameworks that have a “clean up” function that you might not have called. A good example is UIGraphicsEndImageContext() The Context will stay in memory until this function is called. It does not clean up when the function that created the context ends, or when the image involved is set to nil.

Another good example is dismissing ViewControllers. It might make sense to segue to one VC and then segue back, but the segue actually creates a VC. A segue back does not destroy a VC. Call dismissViewControllerAnimated() to remove it from memory.

Read the Class References and double check there are no “clean up” functions.


If you do need Instruments to find a leak, check out the other answer on this question.

like image 81
R Menke Avatar answered Oct 03 '22 16:10

R Menke


enter image description here

click on your apps name in the top-right corner of Xcode.

enter image description here

click on 'edit scheme' in the menu that pops up.

enter image description here

make sure 'RUN' is selected on the left side, then click the diagnostics tab near the top of the window.

under the 'memory management' header check the 'enable Guard Malloc'

you may also want to try checking 'distributed objects' and 'malloc stack' under the 'logging' header

more info on guard malloc, guard edges and scribble can be found here.



hope this helps!

like image 28
MoralCode Avatar answered Oct 03 '22 17:10

MoralCode