I realise that this is pretty old, but I randomly came across it while DuckDucking for something unrelated and I figured I would provide some... update.
First of all, the syntax in Swift is fairly different now from when Filip Roséen answered. There are no more C-style loops, for example. There has also been some work done on the compiler.
Just like the earlier answers explain, you are comparing two different things (growing an array versus initialising an array). However, due to the various changes, Swift is now substantially faster than it was.
Please excuse my Java code if it's suboptimal; this is pretty much the first time I've written Java.
Here's the code I used to dynamically grow an array:
Java:
import java.util.List;
import java.util.ArrayList;
public class java_GrowArray {
public static void main(String[] args) {
long start = System.nanoTime();
List<Integer> intArray = new ArrayList<Integer>();
for (int i = 0; i < 300000; i++) {
intArray.add(0);
}
System.out.println("Time: "+(float)(System.nanoTime()-start)/1000000000 +" s");
}
}
Swift:
import Foundation
let start = CFAbsoluteTimeGetCurrent()
var intArray: [Int] = []
for _ in 0..<300000 {
intArray.append(0)
}
let timeTaken = CFAbsoluteTimeGetCurrent() - start
print("Time: \(timeTaken) s")
And here's the code for just initialising a fixed-size array:
Java:
public class java_InitialiseArray {
public static void main(String[] args) {
long start = System.nanoTime();
int[] intArray;
int i = 0;
intArray = new int[300000];
for (i = 0; i < 300000; i++) {
intArray[i]=0;
}
System.out.println("Time: "+(float)(System.nanoTime()-start)/1000000000 +" s");
}
}
Swift:
import Foundation
let start = CFAbsoluteTimeGetCurrent()
let intArray = [Int](repeating: 0, count: 300000)
let timeTaken = CFAbsoluteTimeGetCurrent() - start
print("Time: \(timeTaken) s")
Timings (median of five runs each):
Grow array (Java): 0.01376 s
Grow array (Swift): 0.01035 s
Init array (Java): 0.00448 s
Init array (Swift): 0.00181 s
Clearly, the performance behaviour of Swift is very different now in 2018 than it was years ago.