Getting Started with Adobe After Effects - Part 6: Motion Blur
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.
Loading

1st Prize - Apple iPad


DOTNET Quiz 2011 - String Performance - Which is Faster and Why?

  • Reviewing the following two snippets of code that build a concatenated string, containing 100,000 entries, which will have better performance and why? How does one mitigate the risks of the other?

    Option 1:

    string result = string.empty;
    for(int i = 0; i < 100000; i++)
    {
        result += "Hello, ";
    }
    Console.Write(result);
    

    Option 2:

    System.Text.StringBuilder result = new System.Text.StringBuilder();
    for(int i = 0; i < 100000; i++)
    {
        result.Append("Hello, ");
    }
    Console.Write(result.ToString());
    
    Posted on 01-22-2011 00:00 |
    mitchel.sellers
    555 · 0% · 66

13  Answers  

Subscribe to Notifications
Previous 1 | 2 Next
  • Score
    10

    In .NET strings are immutable, so each time you append a string to a string, a new object is created. To overcome it, we can use StringBuilder, which presents "mutable string of characters". Internally, it holds a buffer, and each time you append a new string of characters, the characters are added to that buffer. If the buffer is too small, a larger one has to be created. If it comes to the performance of the operations shown above, using StringBuilder is the faster solution, because it doesn't create a new object each time a string is appended.

    Replied on Jan 22 2011 12:36AM  . 
    Maciej Pakulski
    340 · 0% · 120
  • Score
    10

    Option 2 is the much faster option. When a .net string is appended to another string, a new object is created that contains the result; the first and second string are left without change. SO in the sample code, 100.000 new objects get created and 100.000 objects are left behind for garbage collection. This leads to an enormous amount of GC activity and slows down the system. In contrast to that, the StringBuilder is an object that internally manages its memory much more efficient. It allocates blocks of memory and is able to change the "string" value wihtout creating new objects. So in this case the Garbage Collector sees only one object and the string concatenation is handled inside this object. The .net string object is not created undless the ToString() method is called, which makes it 2 creations of objects, which is faster than 100.000.

    Replied on Jan 23 2011 8:34AM  . 
    Guenter
    28 · 6% · 1838
  • Score
    10

    2nd option would be faster.

    The performance difference is not just because strings are immutable and StringBuilder is mutable. Even if the String were mutable, the performance difference would have been there, and that’s because of how it is used in the function.

    Assume for a moment that String is mutable and the same statement is used:

    result += "Hello, ";

    which is same as:

    result = result + "Hello, ";

    This means: add "Hello, " to “result” and store the output in same variable. So there are two operations here – 1: Concatenation and 2: Assignment.

    It will calculate the result of concatenation first, in a different memory location, and then output is copied to “result” variable. The calculation (concatenation) on RHS cannot be performed on same memory location on a variable in use, so a different temporary memory location would be required. Since we assume that String is mutable, same “result” variable can be used as opposed to creating a new one from scratch. But that temporary memory we used for calculation - what happens to that? We are not calling any method of String class that would manipulate its contents directly as opposed to the latter case of calling StringBuilder.Append() method. So even if String were mutable, we would have needed to call a method instead of simple concatenation and variable assignment to equate the performance.

    The StringBuilder class reserves a buffer in the memory for the string it will work with. It keeps putting the contents we provide it in that buffer. When the buffer falls short, it doubles its size. So it doesn’t need to resize it each time. Finally when the ToString() method is called, the buffer is copied to a String variable and outputted. This helps it to perform better than String. Since the StringBuilder class has the large overhead of initial object creation, it should only be used when we would be using it heavily (as in this case of 100000 concatenations). String doesn’t have this overhead. So if you use StringBuilder for a mere few concatenations, we will see a performance degrade instead of performance boost.

    e.g. If we move the declarations inside the loop, the String would outperform StringBuilder, since now a new StringBuilder class needs to be created each time and it is not worth the number of concatenations we perform with it.

    // Option 1:
    for(int i = 0; i < 100000; i++)
    {
        string result = string.Empty;
        result += "Hello, ";
        result += "Hello, ";
    }
    
    // Option 2:
    for(int i = 0; i < 100000; i++)
    {
        System.Text.StringBuilder result = new System.Text.StringBuilder();
        result.Append("Hello, ");
        result.Append("Hello, ");
    }

    You can keep adding result += "Hello, "; and result.Append("Hello, "); to see when StringBuilder starts performing better than String concatenation.

    Replied on Jan 24 2011 2:30AM  . 
    Pradeep Kumar
    299 · 0% · 145
  • Score
    0

    Option 1 is the answer.

    It performs faster string concatenation because, it happens directly in memory instead passing parameter to a function.

    Thanks, AT

    Replied on Feb 9 2011 12:19AM  . 
    Ayyappan Thangaraj
    565 · 0% · 64
  • Score
    9

    Option 2 is surely faster.

    This is because, when you use String += something, then the value of string is copied to new instance every time because the string is immutable. So the code has to copy the value 10000 times or so and that too with growing size of the string. So it will take lot of time to execute. On the other hand, option 2 uses a stringbuilder.append. which uses its own internal buffer to store the current value of string every time it is appended. This value is copied to new one only if the buffer size is reached to its limits, which is not an issue with this example comparing to first option. So option 2 takes much much lesser time (in ms) to execute the code.

    Replied on Feb 9 2011 1:32AM  . 
    anilsoman
    364 · 0% · 109
  • Score
    9

    Option 2 is a winner

    In first, option 1 has a syntax typo - string.empty

    Secondly, I agree the StringBuilder will perform better. The reason for that are listed in previous posts, and are applicable to string + Concatenation.

    To defend string - string.Join for Concatenation would beat StringBuilder.

    Replied on Feb 9 2011 1:59AM  . 
    Igor Zakharov
    158 · 1% · 300
  • Score
    0

    Option 1 is Faster , string resides in stack and string builder in heap. stack access is much faster than the heap. option 1 takes lots of memory since string is immutable Thanks Viju

    Replied on Feb 9 2011 2:56AM  . 
    Viju M N
    2275 · 0% · 5
  • Score
    5

    Option 2 is the best

    Replied on Feb 9 2011 5:07AM  . 
    kraai
    2275 · 0% · 5
  • Score
    9

    Hi,

    Anything over like 256 bytes and I go with a string builder, or a loop over more than 4 or 5...

    Are StringBuilders faster for larger data?

    Yes. When you use a normal string and change it, the .net framework will destroy the current string in memory and create a new one somewhere else in the memory. With a stringbuilder the object isn't destroyed each time it's adapted.

    "The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop".

    Hope this was helpfull.

    Thanks.

    Replied on Feb 9 2011 8:56AM  . 
    merwan
    497 · 0% · 74
  • Score
    10

    Option2 would perform better due to

    1. String Builder is faster compared to string. This is because string builder is mutable and each time a string object is created space is allotted for the new object. String builder class will be used to append a string with out creating new object.
    2. String builder performs faster than concatenation
    3. In the first block leads to more memory burden on the garbage collector. String builder manages memory more efficiently comapared to string
    4. The StringBuilder class allocates buffer in the memory for the string it uses . It places the contents orovided in the buffer. When the buffer is over, its size gets doubled. So it is not required to resize all the time. When the ToString() method is called, the buffer is copied to a String variable for putput .

    Hence option2 is better than option1

    Replied on Feb 17 2011 4:32AM  . 
    Vamshi
    132 · 1% · 376
Previous 1 | 2 Next

Your Answer


Sign Up or Login to post an answer.
Please note that your answer will not be considered as part of the contest because the competition is over. You can still post an answer to share your knowledge with the community.

Copyright © Rivera Informatic Private Ltd.