1

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?

3
  • 1
    let arrayOfStrings = string.components(separatedBy: ":") might be quicker, since you don't need a map() afterward (which is creating another loop). Commented Dec 16, 2019 at 9:05
  • 1
    Where do the strings come from, and how are the substrings used? Perhaps you can work with an array of SubString instead, and avoid the conversion to String. Commented Dec 16, 2019 at 9:33
  • I don't think it's the split which take a lot of time. map is very powerful but not very time-savior (remember that this will make a new object on every iteration) Commented Dec 16, 2019 at 10:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Answers are more helpful (to the author of the question and to future readers of this thread) if they explain the problem and the solution, instead of posting code only.
Thanks, @MartinR. I have attempted to add an explanation.
The only thing I would say about this solution is that components(separatedBy:) is only available if you import Foundation. I'm wondering if it is an NSString method meaning that there are bridging conversions to take into account.
@JeremyP, do you think .split(separatedBy:) will work better?
@sasquatch Does that even exist? Do you mean split(separator:) because that is what the questioner is using and the hypothesis is that it is slow because of the need to convert the components to String

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.