Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.
STRING ITERATION
  • C# allows the characters of a string to be iterated by using a “foreach” or a simple index access within a traditional “for”
    • In this specific case, it is much more efficient to use a traditional “for” loop for iterating over a string
      • One main reason for this is due to the fact that the JIT compiler can optimize “for” loops to remove bounds checking and other operations (it cannot do this with “foreach”).

Using StringBuilder Class

  • C# Strings are immutable objects underneath the hood, so what happens when a string is modified is that a new string is allocated into memory and returned while the old one is marked for garbage collection.
    • Therefore, string manipulation can become a performance intensive operation when done multiple times (like in a loop for example)
  • When performing multiple string manipulation operations on the same string, use the StringBuilder class instead.
    • From MSDN:
      • “There is some overhead associated with creating a StringBuilder object, both in time and memory. On a machine with fast memory, a StringBuilder becomes worthwhile if you're doing about five operations. As a rule of thumb, I would say 10 or more string operations is a justification for the overhead on any machine, even a slower one.”

StringBuilder Class & “+”

  • Using a “+” within a StringBuilder append causes a significant performance hit.
    • So, ALWAYS multiple appends instead of concatenating a string within an append
      • That’s what the StringBuilder is for! e.g.,
      • bool flag = false;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("The value of the flag is ").Append(flag).Append(".");
      • instead of
        • String str = "Hello";
        • str = str + "Abhi";

Char/Byte Arrays

  • Sometimes using character arrays can be significantly more efficient than using strings since characters are value types that take up 2 bytes while Strings are reference types that take up a minimum of 20 bytes.
  • Even better performance can be achieved when using ASCII Strings by converting to a byte array since the byte type only needs 1 byte instead of 2 with char
Posted on Monday, October 21, 2013 3:38 PM .net , performance , string , stringBuilder | Back to top


Comments on this post: String Optimizations

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net