Categories
Uncategorized

Concatenating strings in Swift: Which way is faster?

which is faster

Creative Commons photo by Jaguar MENA. Click to see the source.

Stack Overflow user “James” asked:

Which is the quickest, and most efficient way to concatenate multiple strings in Swift 2?

// Solution 1...
let newString:String = string1 + " " + string2
// ... Or Solution 2?
let newString:String = "\(string1) \(string2)"

Or is the only differentiation the way it looks to the programmer?

It’s not worth worrying about the speed of string concatenations when you’re doing them, once, a dozen, a hundred, or even a thousand times. It may start to matter with larger quantities of larger strings. I decided to run a quick and dirty benchmarking test, which you should take with the appropriate number of grains of salt. Here’s the important part of my code:

let string1 = "This"
let string2 = "that"
var newString: String

let startTime = NSDate()
for _ in 1...100_000_000 {
  // Here's the concatenation:
  newString = string1 + " " + string2
}
print("Diff: \(startTime.timeIntervalSinceNow * -1)")

You may have noticed that I used _ (underscore) characters to make the size of the for loop, 100000000, easier to read, just as we in North America use commas and people elsewhere use spaces or periods. Swift, along with a number of programming languages, lets you do this — take advantage of this and make your code easier to read when dealing with large numbers!

Using the + operator to concatenate strings as shown in James’ example, here’s the average time as reported by the app running in Debug mode over a dozen runs:

  • 1.4 seconds on the simulator on my MacBook Pro (2014 15″ model, 2.5GHz i7, 16GB RAM), and
  • 1.3 seconds on my iPhone 6S

Then, after changing the line after the Here’s the concatenation comment to:

newString = "\(string1) \(string2)"

I ran it again and got these results over a dozen runs:

  • 50.9 seconds on the simulator
  • 88.9 seconds on the iPhone 6S

Running on the phone, the + method is almost 70 times faster, which is a significant difference when concatenating a large number — 100 million — strings. If you’re concatenating far fewer strings, your better bet is to go with the option that gives you the more readable, editable code. For example, this is easier to follow and edit:

"Hello, \(userName), and welcome to \(appSectionName)!"

than this:

"Hello, " + userName + ", and welcome to " + appSectionName + "!"

One reply on “Concatenating strings in Swift: Which way is faster?”

Comments are closed.