user1306322
user1306322

Reputation: 8721

Finding faster ways to concatenate huge strings

I'm making an app that converts images into textual RRR GGG BBB  string arrays.

It works very fast with small images, but when the pixel count of input image is very high, the app slows down progressively.

The application runs x,y loop through all the pixels of input image, scans each pixel and adds its RGB formatted values to the final string which will be saved as text after the whole image is scanned.

With help of built-in profiler I found out that the System.String.Concat(string,string) takes more and more time the bigger the final string gets.

I then tried making a temporary string that will save the result of calculations of 1 row and before entering the next row, add it to the final string. Now it works about ten times faster, but still closer to the end, performance drops.

But in the end all my test images are smaller than the real ones are going to be. How do I keep concatenation speed high with even bigger images?

Upvotes: 2

Views: 3816

Answers (6)

YoryeNathan
YoryeNathan

Reputation: 14522

As everyone said, yes, use StringBuilder.

BUT

If you already have the strings to concatenate in the form of some collection, String.Join() proved to be faster.

Just note that.

Upvotes: 3

Valeriy Gorbatikov
Valeriy Gorbatikov

Reputation: 3519

StringBuilder designed to work with huge and complex strings.

Upvotes: 0

Stian
Stian

Reputation: 1299

Use StringBuilder like this:

//add reference
using System.Text

//create string builder
StringBuilder sb = new StringBuilder();
//add items to it
sb.Append("some text");
sb.Append(" more text");

Upvotes: 0

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

To elaborate on @abatishchev's answer:

When you concatenate strings, you're actually creating a new string instance for each concatenation, so you're allocating thousands (millions?) of tiny strings all the time. A StringBuilder, however, uses an internal character buffer to manage the string as it is built, and avoids these frequent allocations.

Usage is like this:

StringBuilder sb = new StringBuilder();
foreach (Pixel pixel in myPixels)
{
    sb.Append(ConvertToString(pixel));
}

string myString = sb.ToString();

Upvotes: 4

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Use String.Join("", myarray);

Upvotes: 2

abatishchev
abatishchev

Reputation: 100258

Use System.Text.StringBuilder:

var sb = new StringBuilder();
sb.Append(r);
sb.Append(g);
sb.Append(b);

string result = sb.ToString();

This class is designed especially for fast string concatenation. I don't know anything faster (for general case) that it.

Upvotes: 8

Related Questions