C# simple performance improvement
1、String Split()
- In C#, there are 10
Split()
overloaded methods
- General usage
static void SplitChar()
{
var str = "Hello|World";
// 实例化秒表对象
var s1 = new Stopwatch();
s1.Start();
_ = str.Split('|');
Console.WriteLine($"SplitChar ElapsedTicks:{s1.ElapsedTicks}");
}
- Optimized writingCreate an array of characters and pass them as parameters to the
Split()
method
static void SplitCharArray()
{
var str = "Hello|World";
// 实例化秒表对象
var s1 = new Stopwatch();
s1.Start();
_ = str.Split(new char[] {
'|' });
Console.WriteLine($"SplitCharArray ElapsedTicks:{s1.ElapsedTicks}");
}
The test results, it is obvious that the efficiency of using character arrays is much higher
2、String Equals()
- Check
str
whether the value of the variable is equal to the string“Akshay”
, and, don’t know why,str
the value isnull
static void Equals1()
{
try
{
string str = null;
Console.WriteLine(str.Equals("Hello World") ? "IF" : "ELSE");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The above writing, our program throws aNull referenceabnormal
str
TheEquals()
method not used , but“Akshay”
theEquals()
method used
static void Equals2()
{
try
{
string str = null;
Console.WriteLine("Hello World".Equals(str) ? "IF" : "ELSE");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
After changing our thinking, our program outputs the result we defined
3、Adding Strings()
- Benchmark string interpolation, string format, string concat, and string builder
static void AddStrings()
{
string str = "Hello";
string str1 = "World";
var s1 = new Stopwatch();
//String Interploation
s1.Start();
_ = $"{str} {str1} is an author";
Console.WriteLine($"String Interpolation {s1.ElapsedTicks}");
//String Format
s1.Restart();
_ = string.Format("{0},{1} is an author", str, str1);
Console.WriteLine($"String Format {s1.ElapsedTicks}");
//String Concat
s1.Restart();
_ = string.Concat(str, str1, " is an auther");
Console.WriteLine($"String Concat {s1.ElapsedTicks}");
//StringBuilder
s1.Restart();
StringBuilder sb = new StringBuilder();
sb.Append(str);
sb.Append(str1);
sb.Append(" is an auther");
_ = sb.ToString();
Console.WriteLine($"StringBuilder {s1.ElapsedTicks}");
}
Four different methods to add stitching together two strings, four methods string.Concat()
when used happened
The test results suggest that the use string.Concat()
for string concatenation method
4、List.Count() Vs List.Any() Vs List.Count
- Before iterating, use
List.Count()
methods to check if the lib has data or if it is empty. Here compareList.Count()
andList.Any()
method execution time
static void ListCountAndAny()
{
var watch = new Stopwatch();
var strs = new List<string>()
{
"Hello",
"World",
"CSahrp",
"Years"
};
watch.Start();
if (strs.Count() > 0) {
}
Console.WriteLine($"List.Count() {watch.Elapsed}");
watch.Restart();
if (strs.Any()) {
}
Console.WriteLine($"List.Any() {watch.Elapsed}");
watch.Restart();
if (strs.Count > 0) {
}
Console.WriteLine($"List.Count {watch.Elapsed}");
}
Count()
Methods Any()
save time than methods. But using Count
attributes directly takes less time
5、Array Length
- Developers tend to use
Array.Length
as iteration conditions in for loops , but what we need to know is thatLength
attributes are called for each iteration .It is better to store it in a variable and use that variable as the iteration condition
The length of the array is directly used as the iteration condition
static void ArrayLengthInLoop()
{
var watch = new Stopwatch();
string[] names = new[] {
"Akshay", "Patel", "Panth" };
watch.Start();
for (int i = 0; i < names.Length; i++) {
}
Console.WriteLine($"Array.Length in the Loop: {watch.Elapsed}");
}
The length of the array, stored in a variable, and use the variable as the iteration condition
static void ArrayLengthInVariable()
{
var watch = new Stopwatch();
string[] names = new[] {
"Akshay", "Patel", "Panth" };
watch.Start();
int k = names.Length;
for (int i = 0; i < k; i++) {
}
Console.WriteLine($"Array.Length in a Variable: {watch.Elapsed}");
}
Save the time to obtain the length of the array except for the first time, and improve a certain degree of efficiency
There is a certain error in the test result, just refer to it