Add elements to an array like a pro
It’s well known that merging arrays through plus operator cause the compilation process to take much longer. But what about an execution time? As could be expected the winner can be only one.
Appending elements is more than hundred times faster than merging arrays! It’s true!
I have started from appending one element and merging the base array with a single element array. The results were comparable but then decided to check five elements array. Plus operator looks cool, but it’s so sloooow.
Consider that repeatCount
equals 10,000. Probably that performance loss would be almost unnoticeable in most cases. But it’s still one of the most irritating Swift issues and sometimes causes even too popular compiler error saying that expression was too complex to be solved in reasonable time.
On the other hand plus operator works great when you’re merging two arrays into a new one.
1 2 3 4 5 6 7 8 9 10 | let array1 = Array(stride(from: 1, to: 101, by: 1)) let array2 = Array(stride(from: 101, to: 201, by: 1)) _ = self.array1 + self.array2 // is just as fast as this var newArray = Array(self.array1) self.array2.forEach { element in newArray.append(element) } |
PS. Testing environment was Xcode 8.0 (8A218a), iOS 10 simulator and Swift 3.
About the author
Ready to take your business to the next level with a digital product?
We'll be with you every step of the way, from idea to launch and beyond!