Posts for Tag: structs

The Importance of Being `final`

[UPDATE - Swift 1.2 from Xcode 6.3 Beta 2 brings performance benefits to non-final properties and methods making final unnecessary for performance from that time - see my initial reaction to Beta 2. I still recommend final where possible as it avoids need to consider effects of an object being subclassed and methods overwritten that change the behaviour.]

This post is intended to quantify, explain and show the performance hit that you take from not adding the word final to your classes (or their properties and methods). The post was triggered by a blog post complaining about Swift performance and showing some performance figures where Swift was significantly slower than Objective-C. In the optimised builds that gap could be closed just by adding a single final keyword. I'm grateful to David Owens for showing the code he was having trouble and giving me a base to demonstrate the difference final can make without it being me cherry picking any code of my choosing.

As with most performance issues this doesn't matter most of the time. Most code is waiting on user input, network responses or other slow things and it really doesn't matter that much if the code is being accessed a few times a second. However when you have got performance critical code and in particular that inner loop that is being executed hundreds of thousands of times a second it can make a huge difference.

What does final do