Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the memory cost of using all static methods in a struct/class?

Does creating a lot of static/class functions in Swift class/struct result in unreleased memory when the iOS app is running? Is it a good practice to use static/class functions for Utility classes?

How different is the memory cost between using static/class functions in Swift and using

+ (void) someMethod;

in Objective-C?

like image 537
R P Avatar asked Feb 24 '17 05:02

R P


1 Answers

Does creating a lot of static/class functions in Swift class/struct result in unreleased memory when the iOS app is running?

static and class methods are compiled into your code and will increase your application's size in storage. They won't necessarily increase the application's memory usage, if they're never used. Since static methods can't be overridden like class methods, they can always be statically dispatched. This allows the compiler to better optimize them. In many cases, simple static methods can even be inlined into the place they're called from. It's as if their method body was transplanted directly into the call site.

Is it a good practice to use static/class functions for Utility classes?

Typically it's a good idea to avoid utility classes. Most things that would typically go in a utility class in languages like Java or C# can be done much more nicely with extensions in Swift. fileprivate global functions are also handy when you need a utility function that's only used in a single file. You should only create utility classes if you're you have functions that you would like to use across multiple files or modules.

How different is the memory cost between using static/class functions in Swift and using

+ (void) someMethod;

in Objective-C?

And that's the Objective-C syntax for a class method. Objective-C does not support static methods.

like image 118
Alexander Avatar answered Sep 20 '22 11:09

Alexander