Wednesday, September 08, 2004

Efficient string manipulation

Avoid Returning null Instead of Array, String, or Collection

In almost all situations except when performance can be an issue (e.g.
heavily looped or performance tuned code), null should not be returned
from a method that returns an array, string, collections, ArrayList,
BitArray, HashTable, Queue, SortedList, or Stack. It should not be
necessary for a user of a method to handle a null that is returned
from a method. Instead only empty or zero-length data types such as 0
item arrays, empty strings (String.Empty), and 0 item collections
should be returned.

Avoid Checking String Equality Using == and = Operators

Using == operator in C# and = operator in Visual Basic to compare
strings is slower than using the System.String.Equals method. In
addition, if you need to do case sensitive or insensitive comparisons
the System.String.Compare method is the preferred way to do so. The
String.Compare method can compare two strings based on their
alphabetical sort order as well, something that is important in
developing applications for the international market.

Testing for Empty Strings

The most efficient method to determine if a string is empty is via
it's Length property.

[C#]
if(var1.Length < 1)

[Visual Basic]
If (var1.Length < 1) Then

Avoid Hard Coded String Literals

Use String.Empty rather than "" for empty strings. Other strings
should be placed in a constants class.
[C#]
string var1 = ""; // Avoid
string var2 = String.Empty; // Recommended

[Visual Basic]
Dim var1 As String = "" ' Avoid
Dim var2 As String = String.Empty ' Recommended

0 Comments:

Post a Comment

<< Home