The two most common ways of appending elements to Swift
Arrays are using the
append method and using the
+ operator with another
I generally prefer using the
+ operator since it leads to more concise code, however, I always wondered if we incur a performance hit by (unnecessarily) creating a new array with a single element instead of simply appending the element directly. It turns out, we do.
To quickly benchmark this, we can create a simple
append.swift file with a few lines of code that append 1 million elements to an array:
Once we save the file, we can compile it by running
swiftc append.swift from the command line. Then we can run and time the executable with
time ./append. On my MacBook Pro, the wallclock (“real”) time averages around 0.027s.
While we could have also done this in a Swift Playground or even the REPL, a compiled binary is built with more optimizations and it’s execution time is more stable in nature, leading to benchmarks that are more reliable.
Now let’s try array concatenation:
If we run and time this version of the program, the wallclock time jumps to 0.603s, or a ~20x slowdown. While this is negligible in most cases, if you find yourself frequently adding elements to arrays in performance-sensitive code, it might be worthwhile switching to
swiftc as invoked above was not set to build with optimizations. However, even if the
-O flag is passed,
Array.append remains ~6x faster.