Skip to main content

Posts

Showing posts with the label String

String.Format

In Microsoft.Net most of the objects implement .ToString() function. This is a very powerful function which returns string representation of underlying object. However if it is overused with concation operators like + in C#, it can have serious performace hit for large application. The problem with concatenation is that it create a new string for every concatenation operator and assigns memory to it. If it is just string concatenation you are looking for, use StringBuilder class instead. A better and Microsoft recomended way of formatting strings is to use String.Format. This is a very powerful funation and you would be amazed by the number of formats it support. Once you get hang of it, you will never go back to using .ToString. Here is an example. Say you wany to display current date time. Your normal code would be Response.write("Todays Date is: " + DateTime.Now.ToString("dd/MM/YYYY")); A better way would be Reponse.Write(String.Format("Todays Date is:{0:dd/...

Performance improvement with StringBuilder class

Often we do large string concatenation in our code without giving a thought to performance. Consider following example of string concatenation. string s1 = "orange"; string s2 = "red"; s1 += s2; System.Console.WriteLine(s1); // outputs "orangered" s1 = s1.Substring(2, 5); System.Console.WriteLine(s1); // outputs "ange r" String objects are immutable, meaning that they cannot be changed once they have been created. Methods that act on strings actually return new string objects. In the previous example, when the contents of s1 and s2 are concatenated to form a single string, the two strings containing "orange" and "red" are both unmodified. The += operator creates a new string that contains the combined contents. The result is that s1 now refers to a different string altogether. A string containing just "orange" still exists, but is no longer referenced when s1 is concatenated. Therefore, for performance reasons, lar...

Strings

The @ Symbol The @ symbol tells the string constructor to ignore escape characters and line breaks. The following two strings are therefore identical: string p1 = "\\\\My Documents\\My Files\\"; string p2 = @"\\My Documents\My Files\"; // Copy one character of the string (not possible with a System.String) sb[0] = sb[9]; System.Console.WriteLine(sb); // displays 9123456789 } }