When we create programs, it is very important to make its code optimized. It is because having an optimized code will improve the program's performance, like execution time, code size, etc. It will make your code run faster, use fewer server resources, and make your code easier to debug and maintain.
Here are some ways to make your code optimized:
- Use string.format instead
of string concatenation (+). The format function is faster than the +
operator.
Example:
szConfirmMsg = “Are you sure you
want to change the store number on audit
id ” + auditId + “ from “ + oldStoreNo + “ to “ + newStoreNo + “?”;
szConfirmMsg
= string.Format(“Are you sure you want to change the store number on audit id {0} from {1} to {2}?”,
auditId, oldStoreNo, newStoreNo);
- Use System.IO.Path class if dealing with path and filenames.
Example:
Searching if file is valid:
string
fileExt = System.IO.Path.GetExtension(fileName);
if
(fileExt.ToLower().Equals(“.csv”))
{
bValid
= true;
}
- Use string.Empty instead
of ‘’ to initialize a string
variable to an empty string. string.Empty
is faster than ‘’ because it
doesn’t create a new object while ‘’
actually creates an object.
Example:
string userMessage = ‘’;
string
userMessage = string.Empty;
- Use string.Equals instead
of the equal operator (= =) to test strings for equality.
Example:
if (szName = = ‘’)
if (a = = b)
if
(szName.Trim().Equals(string.Empty))
if (a.Equals(b))
No comments:
Post a Comment