HelloMoon
HelloMoon

Reputation:

Performant way to build long strings in a loop?

I have a loop that builds up a pretty large string. With every iteration a little string snippet is added to that string, and that string becomes bigger and bigger. Is there something better than using an NSMutableString and appending another string to that?

Upvotes: 0

Views: 104

Answers (1)

groundhog
groundhog

Reputation: 4780

The problem with appending to a string is that unless the string has preallocated all the space required, you're going to need to do some allocations and copying, leading to O(n^2) performance.

A more performant way is to build an NSArray of your list of strings using NSArray:componentsJoinedByString:. Appending to the array is constant time, and since it knows the length of the resulting string before hand, it can provide you the final string in O(n) time.

Upvotes: 2

Related Questions