I am dealing with very large arrays in Swift and came to the conclusion that those are extremely slow when adding elements to it.
I am observing those issues mainly when I use arrays in a Dictionary
.
ex : var array = [String : [String]]
Therefore I decided to benchmark a very simple array
test using playground, thinking the issue came from the array
itself :
var arr = [Int]()
for i in 0..<1_000_000 {
arr.append(i)
}
This code takes forever to complete. Now the same code in C# with a real List
, takes not even a second.
IList list = new List<int>();
for (int i = 0; i < 1000000; i++) {
list.Add(i);
}
I know that Arrays in Swift aren't lists like in other languages where you have the flexibility to pick an ArrayList
, LinkedList
. Swift, re-allocates every time you add a new element, and basically puts all the array in some newer bigger space.
How can we solve this ?
EDIT 1: Hamish pointed out that using a Xcode Playground environment is a terrible idea for performance tracking. He is right, Swift arrays
are as fast as C# when not used in Playground.
EDIT 2: Performance issues with arrays
are not because of the array
itself, but only when using arrays
inside a dictionary. See answers below.