xcode Swift 与 Objective-C 斐波那契数列速度比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28161197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift vs Objective-C Fibonacci Sequence Speed Comparison
提问by xiaowoo
I have a problem. I want to know which one is indeed faster(Swift or Objective-C) because I would like to choose a faster/better one when I start developing an app. According to many sources(For example Apple's WWDC, or http://www.jessesquires.com/apples-to-apples-part-two/), Swift is suppose to be faster.
我有个问题。我想知道哪个确实更快(Swift 或 Objective-C),因为我想在开始开发应用程序时选择一个更快/更好的。根据许多来源(例如 Apple 的 WWDC,或http://www.jessesquires.com/apples-to-apples-part-two/),Swift被认为更快。
I just wrote a simple recursive fibonacci sequence program in both Swift and Objective-C.
我刚刚用 Swift 和 Objective-C 编写了一个简单的递归斐波那契数列程序。
However, when I run fib(35) on the simulator, I get surprising results:
然而,当我在模拟器上运行 fib(35) 时,我得到了令人惊讶的结果:
Objective-C Result:
Objective-C 结果:
:::fib::::9227465:::duration:::0.122813 seconds
:::fib::::9227465:::duration::0.122813 秒
Swift Result
快速结果
:::fib::::9227465 :::duration:::0.606831073760986 seconds
:::fib::::9227465 :::duration::::0.606831073760986 秒
Now, I even ran the Swift version in all Swift Compiler Optimization level(for Debug), which is None, Fastest, Fastest-Unchecked. I also play around with the Code Generation Optimization Level to None, Fast....Fastest Aggressive Optimization. However all Swift results are something close to 0.6 milliseconds
现在,我什至在所有 Swift 编译器优化级别(用于调试)中运行 Swift 版本,即无、最快、最快未检查。我还将代码生成优化级别设置为无、快速....最快的积极优化。然而,所有 Swift 结果都接近 0.6 毫秒
Now the last thing I can think of is may be, I am comparing an Apple to Orange? Do you guys see anything I am missing here? Is there anything else I have to turn on(other than Optimization levels for Swfit Compiler & Apple LLVM Code Generation) to make Swift programs run faster?
现在我能想到的最后一件事可能是,我正在将 Apple 与 Orange 进行比较?你们看到我在这里遗漏了什么吗?还有什么我必须打开的(除了 Swfit 编译器和 Apple LLVM 代码生成的优化级别)以使 Swift 程序运行得更快?
Any suggestions or comments are welcome and appreciated ! ^^ !
欢迎和赞赏任何建议或意见!^^!
Objective-C Version
Objective-C 版本
-(int)fib:(int)num{
if (num == 0) {
return 0;
}
if (num == 1) {
return 1;
}
return [self fib:num - 1] + [self fib:num - 2];
}
Swift Version
迅捷版
func fib(num: Int) -> Int{
if(num == 0){
return 0;
}
if(num == 1){
return 1;
}
return fib(num - 1) + fib(num - 2);
}
Objective-C Time Measurement
Objective-C 时间测量
NSTimeInterval start = [[NSDate date] timeIntervalSince1970];
int result = [self fib:35];
NSTimeInterval end = [[NSDate date] timeIntervalSince1970];
NSTimeInterval duration = end - start;
NSLog(@":::fib::::%d:::duration:::%f",result,duration);
Swift Time Measurement
快速时间测量
var start = NSDate().timeIntervalSince1970;
let result = fib(35);
var end = NSDate().timeIntervalSince1970;
var duration = end - start;
println(":::fib::::\(result) :::duration:::\(duration)");
回答by fyell
Lot of things to consider when deciding which of the two programming languages are faster. I did a couple of benchmarks (https://github.com/vsco/swift-benchmarks) between Swift and Objective-C and I found that in certain cases Swift was faster and in other cases Objective-C was faster. For example, using struct objects in Swift will offer tremendous performance gains if you need to operate over a large amount of data. In contrast, using non-struct objects made Swift significantly slower than it's Objective-C counterparts.
在决定两种编程语言中的哪一种更快时,需要考虑很多事情。我在 Swift 和 Objective-C 之间做了几个基准测试 ( https://github.com/vsco/swift-benchmarks),我发现在某些情况下 Swift 更快,而在其他情况下 Objective-C 更快。例如,如果您需要对大量数据进行操作,在 Swift 中使用 struct 对象将提供巨大的性能提升。相比之下,使用非结构对象使 Swift 比它的 Objective-C 对应物慢得多。
Also how you use certain features in Swift is very crucial to how well it will perform. Take this function for example:
此外,您如何使用 Swift 中的某些功能对其执行效果非常关键。以这个函数为例:
class func shuffleGenericObjects<T>(inout array:[T]) {
for (var i = 0; i < array.count; i++) {
let currentObject: T = array[i]
let randomIndex = Int(arc4random()) % array.count
let randomObject: T = array[randomIndex]
array[i] = randomObject;
array[randomIndex] = currentObject
}
}
Sure it works great for minimizing repetitive code, but when I executed this method over 1 million Int objects, it took roughly 32 seconds to finish. As oppose to the non-generic implementation, which only took 0.181 seconds.
当然,它可以很好地减少重复代码,但是当我执行这个方法超过 100 万个 Int 对象时,大约需要 32 秒才能完成。与非通用实现相反,它只需要 0.181 秒。
I also recommend not to use NSDate
functions for benchmarking in Swift. I came across a few bugs that caused NSDate
to return incorrect times. It's much better to put your benchmarks in an XCTestCase
and use the measureBlock()
function.
我还建议不要NSDate
在 Swift 中使用函数进行基准测试。我遇到了一些导致NSDate
返回错误时间的错误。将您的基准放在一个XCTestCase
并使用该measureBlock()
功能要好得多。
回答by Rob
The choice of Fibonacci as your benchmark is a little ironic, because in WWDC 2014 video Advanced Swiftthey use the Fibonacci sequence as an example of how you can write a generic memoize
function that is several orders of magnitude faster.
选择斐波那契数作为基准有点讽刺,因为在 WWDC 2014 视频Advanced Swift 中,他们使用斐波那契数列作为示例,说明如何编写一个memoize
速度快几个数量级的泛型函数。
func memoize<T: Hashable, U>(body: ((T)->U, T) -> U) -> (T)->U {
var memo = [T: U]()
var result: ((T)->U)!
result = { x in
if let q = memo[x] { return q }
let r = body(result, x)
memo[x] = r
return r
}
return result
}
Where you can then:
你可以在哪里:
let fib = memoize { fib, x in x < 2 ? x : fib(x - 1) + fib(x - 2) }
let result = fib(35)
Now, clearly, it's unfair to compare this to a non-optimized Objective-C recursive Fibonacci function, because this will leave it in the dust. I'm not even sure I agree with all of the WWDC's conclusions regarding the merits of the Swift generic memoize
implementation. But the performance improvement is startling.
现在,很明显,将其与未优化的 Objective-C 递归斐波那契函数进行比较是不公平的,因为这将使其成为尘土。我什至不确定我是否同意 WWDC 关于 Swift 通用memoize
实现的优点的所有结论。但性能提升是惊人的。
There are plenty of patterns where a naive translation of Objective-C code will result in slower Swift implementations. In particular, far more dramatic than your example where the Swift code was a little slower, I've been startled by simple situations in which it's quite easy to write a routine in Swift that looks logically very similar (or even more elegant), but is really much, much slower (or at least prior to the app developer refactoring the Swift implementation a bit).
在许多模式中,Objective-C 代码的幼稚翻译会导致 Swift 实现速度变慢。特别是,比你的 Swift 代码慢一点的例子更具戏剧性,我被一些简单的情况吓到了,在这种情况下,用 Swift 编写一个在逻辑上看起来非常相似(甚至更优雅)的例程非常容易,但是确实要慢得多(或者至少在应用程序开发人员重构 Swift 实现之前)。
Bottom line, I would personally hesitate to draw any simple conclusions of Swift is faster than Objective-C, or vice versa. I suspect that there are some algorithms/applications where Swift is faster and others where it is not.
最重要的是,我个人不会轻易得出 Swift 比 Objective-C 快的任何简单结论,反之亦然。我怀疑有些算法/应用程序 Swift 更快,而其他算法/应用程序则不然。
Furthermore, you say that the regarding the choice of programming language that you "would like to choose a faster/better one". I would contest that the "faster" language is always "better" one (otherwise, we'd all still be writing assembly code). Often, the choice of language is less the raw computational efficiency of the code, and more the effectiveness of the developer. We should all chose the language in which we can write the most robust code, do so in the most cost-efficient manner, writing code that is most easily maintained in the future, and deliver a superlative user experience.
此外,您说关于编程语言的选择,您“想选择一种更快/更好的语言”。我会争辩说“更快”的语言总是“更好”的语言(否则,我们仍然会编写汇编代码)。通常,语言的选择不是代码的原始计算效率,而是开发人员的效率。我们都应该选择可以编写最健壮代码的语言,以最具成本效益的方式编写代码,编写未来最容易维护的代码,并提供最佳的用户体验。
Whether that language is Swift or Objective-C is a matter of opinion and is not for this forum.
该语言是 Swift 还是 Objective-C 是一个见仁见智的问题,不适合本论坛。
回答by Choppin Broccoli
Your code looks good, but you can't generalize the speediness of a programming language on one situation like that. In Apple's Keynote last year, they said "complex object sort" was faster in Swift. There are probably a couple things faster in Objective-C, but generally, Swift is supposed to be the faster language.
您的代码看起来不错,但您无法在这种情况下概括编程语言的速度。在去年 Apple 的 Keynote 演讲中,他们说“复杂对象排序”在 Swift 中更快。Objective-C 中可能有一些更快的东西,但一般来说,Swift 应该是更快的语言。