Swift显式与推理类型:性能 [英] Swift Explicit vs. Inferred Typing : Performance

查看:155
本文介绍了Swift显式与推理类型:性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Swift的教程( http:// www .raywenderlich.com / 74438 / swift-tutorial-a-quick-start ),并且它预先定义为不明确设置类型,因为它更可读。

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 ?

例如,将: var hello:Int = 56 比这更有效: var tutorialTeam = 56

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

推荐答案

使用显式类型的代码和使用类型推断的代码之间存在性能上的差异

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

上述代码推断 num 是一个 Int 用整数文字初始化。但是,您可以强制它成为 Double ,如下所示:

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

这篇关于Swift显式与推理类型:性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆