0

I am learning Swift 3 and I compared the speed to Rust and it's roughly 4 times slower. I don't know x86 assembly so I am asking why is it slower?

Swift 3 Code:

let n = 10000000
var v = [Int]()
var sum = 0
for i in 0..<n {
    v.append(1)
    sum += v[i]
}
print(sum)

swiftc sum.swift -O

Here's the equivalent Rust code:

fn main() {
    let n = 10_000_000;
    let mut v = Vec::new();
    let mut sum = 0;
    for i in 0..n {
        v.push(1);
        sum += v[i];
    }
    println!("{}", sum);
}

rustc -o sumrs sum.rs -O
jimjampez
  • 1,766
  • 4
  • 18
  • 29
  • Did you only time the summation or all of the code? Because there is more going on than just summation which could affect the runtime. – Keiwan Nov 22 '16 at 17:02
  • Yeah, I have measured all of the code as I haven't worked how to measure elapsed time in Swift. I noticed using CInt and -Ounchecked as got it on par with Rust – jimjampez Nov 22 '16 at 17:12
  • 1
    I unfortunately can't help you with your initial question but here's a link to another SO question on how you can benchmark Swift code: http://stackoverflow.com/questions/25006235/how-to-benchmark-swift-code-execution – Keiwan Nov 22 '16 at 17:17

0 Answers0