Matt Rajca

blog projects github twitter email

Benchmarking Swift: Array.append vs Concatenation

October 22, 2016

The two most common ways of appending elements to Swift Arrays are using the append method and using the + operator with another Array:

  
    var list = [Int]()
    list += [5]
    

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:

  
    var list = [Int]()

    for i in 0..<1_000_000 {
        list.append(5)
    }
    

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:

  
    var list = [Int]()

    for i in 0..<1_000_000 {
        list += [5]
    }
    

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 append.

Update: swiftc as invoked above was not set to build with optimizations. However, even if the -O flag is passed, Array.append remains ~6x faster.

Update 2: Ben Ng has now committed an optimization pass to Swift that addresses this.