在项目开发中,C#正确使用字符串操作可以减少垃圾回收压力。本文讲述在C#中的几种字符串操作方法,可以提高程序性能。
<pre class="code-snippet__js" data-lang="cs"> string str="";
if (str.Length == 0){
Console.WriteLine("为空!");}
或者使用if(str==.Empty)其次使用if(str=="")。
2、使用.Empty给一个空字符串变量赋初始值
.Empty不占用内存空间,而str==""的方式是具体的实现c#timerc#timer,是占用空间的。
string str=string.Empty;
3、避免不必要的字符串、类操作而使用.
.可实现忽略字符串大小写,而、这类方法均会重新生成字符串对。
string str1="公众号:dotNet开发跳槽";
string str2="公众号:DOTNet开发跳槽";
//推荐使用
if (string.Compare(str1,str2,true)==0)
Console.WriteLine("相等!");
//不推荐
if (str1.ToUpper()==str2.ToUpper())
Console.WriteLine("相等!");
4、正确使用进行字符串拼接操作
如果要构造一个较长的字符串,尤其是拼接超过10次时(经验值),就应使用做字符串拼接操作。
Stopwatch timer = new Stopwatch();
string s = null;
timer.Start();
for (int i = 0; i < 66666; i++)
{
s += (i + 1) + "、Dotnet开发跳槽 ";
}
timer.Stop();
decimal micro = timer.Elapsed.Ticks / 10m;
Console.WriteLine($"拼串耗时:{micro}");
StringBuilder sb = new StringBuilder();
timer.Restart();
for (int i = 0; i < 66666; i++)
{
sb.Append(i + 1);
sb.Append("、Dotnet开发跳槽 ");
}
string t = sb.ToString();
timer.Stop();
micro = timer.Elapsed.Ticks / 10m;
Console.WriteLine($"StringBuilder耗时:{micro}");
另外避免滥用类似str1+str2+str3+str4的字符串拼接操作会被编译为 .(str1,str2,str3, str4),效率反而高于。
5、创建应指定初始大小
默认的初始大小为16,一旦超过即需要一次并增加GC压力。建议根据经验值为其指定初始大小,比如最大有128个中文字符,那么初始为256。
StringBuilder sb = new StringBuilder(256);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。