Swift Tip: A Quick Tip For String Performance

In this new post series we'll show highlights of Swift Talk, our subscription video series. Today, we'll show a very nice trick by Ole Begemann to increase String processing performance.

In Swift Talk 79, we try to improve CSV string parsing performance by measuring time and comparing the performance of various techniques. To write a performance test, we wrap the parsing of the loaded string in an XCTest measure block:

								func testPerformance() {
    let bundle = Bundle(for: ParseCSVTests.self)
    let url = bundle.url(forResource: "small", withExtension: "txt")!
    let data = try! Data(contentsOf: url)
    let string = String(data: data, encoding: .isoLatin1)!

    measure {
        _ = parse(lines: string)


The change is a rather obscure tip we got from Ole:

								let string = String(data: data, encoding: .isoLatin1)! + ""


When we append an empty string to the test string, we get a performance improvement of 18 percent:

The reason for the performance gain: a string can be backed by a Swift String or an NSString. By appending an empty string, we force it to be backed by a Swift String, with which our algorithm works much faster.

In the remainder of the episode, we also show a technique suggested by Matt Gallagher from Cocoa with Love, and increase performance by another 83%. The episode and transcript are available for subscribers, and are part of the Swift, The Language collection.

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts