Aleksey M.
Aleksey M.

Reputation: 1

Swift split strings efficiently

I have a lot of strings like this one:

"substring1:substring2:...:substring9"

So the number of substrings in string is always 9, and some substrings in string may be empty.

I want to split the string by ":" into array of strings and i do it like this:

let separator = Character(":")

let arrayOfStrings = string.split(separator: separator, maxSplits: 8, omittingEmptySubsequences: false).map({ String($0) })

For example for 13.5k strings it took about 150ms to convert them into arrays of strings.

Is there any other method that is more efficient in terms of time for this task?

Upvotes: 0

Views: 2862

Answers (1)

saurabh
saurabh

Reputation: 6775

Try this:

 let arrayOfStrings = string.components(separatedBy: ":")

This should improve performance as it doesn't use .map(), which isn't really required in your case.

Or

As @Martin R suggested, if you can work with an array of SubString instead, the following should perform better:

let arrayOfStrings = string.split(separatedBy: ":")

split returns [Substring] which only uses references, does not allocate a new String and should be faster. Also, .split is a method on String, (unlike .component which is a method on NSString) and hence there is no bridging conversion as pointed by @JeremyP.

Upvotes: 2

Related Questions