elias_d
elias_d

Reputation: 173

How to efficiently concat QStrings

I want to concat a tree structure of QStrings into a single QString.

If I understand correctly, QStrings are immutable like Java-Strings, so similar reasons why you use Java's StringBuilder should apply.

Using the % operator seems only to improve the efficiency of a single statement, so would probably not help me much since I need to concat over several nested loops.

I could use a std::stringstream, but that would mean transforming each single QString into a C-string or std-string first, presumably with performance cost.

Would using a QTextStream help?

Or is there some better possibility?

Upvotes: 3

Views: 3534

Answers (1)

Andrew Kashpur
Andrew Kashpur

Reputation: 746

If you concatinate large ammount of string via + operator or append method, it is inefficient due to memory reallocations. In order to avoid said reallocations you need to calculate amount of memory result of concatination need, allocate said amount to char* buffer, copy raw data of every string you concatinate in appropriate place in buffer (via memcpy for example). Then constract resulting string object from char* buffer.

Upvotes: 1

Related Questions