Search code examples
performancetypescompiler-constructionswift

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


Solution

  • 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