1

I use code like this to build one string from an string array:

class ActionCMD {   // "class" to avoid value copies when updating string members
    var cmds = [String]()   // simply the list of all strings to speed up inserting
    var cmd : String { return cmds.reduce("", +) }   // resulting string
}

But for 35.000 strings it needs 15 min. Is there a better (quicker) way to do the concatenating?

6
  • 2
    How about return cmds.joined() Commented Nov 24, 2019 at 11:35
  • 1
    How do you get your input set of 35000 String? Perhaps some preprocessing can be made to speed things up Commented Nov 24, 2019 at 11:37
  • stackoverflow.com/q/25827033/1187415 Commented Nov 24, 2019 at 11:53
  • Is it definitely this code that takes 15 minutes and not the loading of the 35,000 strings? Commented Nov 24, 2019 at 11:54
  • 1
    Executing your code, the reduce, in a playground takes 0.0003 seconds for me on a few year old MacBook Pro so even though my test is far from precise I feel the issue must lay somewhere else for you Commented Nov 24, 2019 at 12:20

1 Answer 1

2

You should avoid creating intermediate strings. Instead, mutate the previously accumulated string, by using either:

cmds.reduce(into: "", { $0 += $1 })

or :

cmds.joined()

or simply :

var cmd = ""
for i in cmds.indices {
    cmd += cmds[i]
}

More on String concatenation here

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

3 Comments

Thanks, I will try "joined". I don't use a loop to do it by my own. Like to use library functions.
Its now fast! :-) I think 30 s instead of minutes! Thanks a lot.
@Peter71 That's quite a difference! Glad I could be of help :)

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.