Swift 与 Objective-C 的性能对比 [英] Performance of Swift vs Objective-C

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

问题描述

我只是比较 SwiftObjective-C.为此,我使用 NSDate 来测量花费的时间,但我发现 Swift 和 Objective-C 之间存在很大差异.我刚刚运行了一个空的 for 循环 100,000 次.这是我的代码,

I am just comparing the performance of Swift and Objective-C. For that, I am using NSDate to measure the time taken, but I am getting a big difference between Swift and Objective-C. I just ran an empty for loop 100,000 times. Here is my code,

在 Objective-C 中,

In Objective-C,

NSDate * start = [NSDate date];

for (int i=0; i<=100000; i++) {

}

NSDate * end = [NSDate date];

double timeTaken = [end timeIntervalSinceDate:start] * 1000;

timeTaken 为 0.24 毫秒

timeTaken is 0.24 milliseconds

在 Swift 中,

var start = NSDate()

    for i in 0...100000

    {

    }

    var end = NSDate()

    var timeTaken = end.timeIntervalSinceDate(start) * 1000

timeTaken 在 Swift 中是 74 毫秒,这与 Objective-C 相比有很大的不同.

timeTaken is 74 milliseconds in Swift, which is a big difference when compared to Objective-C.

我在测量中做错了什么吗?

Am I doing anything wrong here in the measurement?

推荐答案

你在做什么纯属无稽之谈.这个循环的性能如何并不重要,因为它不会在实际代码中发生.本质区别在于,在 Swift 中,循环将在每个步骤进行溢出检查,这是由于语言定义而导致的副作用.在 Objective-C 中,情况并非如此.

What you are doing is pure nonsense. It doesn't matter what the performance of this loop is, because it doesn't happen in real code. The essential difference is that in Swift, the loop will do overflow checks at each step which are a required side effect due to the language definition. In Objective-C, that's not the case.

至少你需要写出真正有意义的代码.

At the very least you need to do code that does actually meaningful things.

我做了一些真实的测试,结果是: 1. Swift 和普通 C 的低级操作速度相当.2. 发生溢出时,Swift 会终止程序以便您注意到溢出,而 C 和 Objective-C 会默默地给您无意义的结果.试试这个:

I've done some real tests, and the results were: 1. Speed of Swift and plain C for low-level operations are comparable. 2. When on overflow happens, Swift will kill the program so you can notice the overflow, while C and Objective-C will silently give you nonsense results. Try this:

var i: Int = 0
var s: Double = 0.0

for (i in 1 .. 10_000_000_000) { s += Double (i * i) }

Swift 会崩溃.(任何认为这很糟糕的人都对编程一无所知).在 Objective-C 中同样的事情会产生无意义的结果.用

Swift will crash. (Anyone who thinks that's bad hasn't got a clue about programming). The same thing in Objective-C will produce a nonsense result. Replace the loop with

for (i in 1 .. 10_000_000_000) { s += Double (i) * Double (i) }

并且两者都以相当的速度运行.

and both run at comparable speed.

这篇关于Swift 与 Objective-C 的性能对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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