Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Explicit vs. Inferred Typing : Performance

I'm reading a tutorial about Swift (http://www.raywenderlich.com/74438/swift-tutorial-a-quick-start) and it preconized to not set type explicitly because it's more readable this way.

I do not really agree about this point but that's not the question. My question is : Is it more efficient, in terms of performance (compiler...) to set type explicitly ?

For example, would this : var hello: Int = 56 be more efficient than this : var tutorialTeam = 56

like image 306
user2462805 Avatar asked Jul 05 '14 17:07

user2462805


2 Answers

There is no difference in performance between code that uses explicit types and code which uses type inference. The compiled output is identical in each case.

When you omit the type the compiler simply infers it.

The very small differences observed in the accepted answer are just your usual micro benchmarking artefacts, and cannot be trusted!

Whether or not you include the explicit type is a matter of taste. In some contexts it might make your code more readable.

The only time it makes a difference to your code is when you want to specify a different type to the one which the compiler would infer. As an example:

var num = 2

The above code infers that num is an Int, due to it being initialised with an integer literal. However you can 'force' it to be a Double as follows:

var num: Double = 2
like image 143
ColinE Avatar answered Oct 04 '22 01:10

ColinE


From my experience, there's been a huge performance impact in terms of compilation speed when using explicit vs inferred types. A majority of my slow compiling code has been resolved by explicitly typing variables.

It seems like the Swift compiler still has room for improvement in this area. Try benchmarking some of your projects and you'll see a big difference.

Here's an article I wrote on how to speed up slow Swift compile times and how to find out what is causing it.

like image 20
panupan Avatar answered Oct 04 '22 02:10

panupan