C#中判断空字符串的3种方法性能分析
3種方法分別是:
string a="";
1.if(a=="")
2.if(a==String.Empty)
3.if(a.Length==0)
3種方法都是等效的,那么究竟那一種方法性能最高呢?本人用實(shí)驗(yàn)說明問題。
建立3個aspx頁面(為什么用網(wǎng)頁,主要是利用Microsoft Application Center Test?)
WebForm1.aspx
private void Page_Load(object sender, System.EventArgs e)
??{
???string a="";
???for(int i=0;i<=1000000;i++)
???{
????if(a=="")
????{
????}
???}
??}
WebForm2.aspx private void Page_Load(object sender, System.EventArgs e)
??{
???string a="";
???for(int i=0;i<=1000000;i++)
???{
????if(a==String.Empty)
????{
?????
????}
???}
??}
WebForm3.aspx
private void Page_Load(object sender, System.EventArgs e)
??{
???string a="";
???for(int i=0;i<=1000000;i++)
???{
????if(a.Length==0)
????{
????}
???}
??}
?在Microsoft Application Center Test?下建立3個壓力測試項(xiàng)目:
測試結(jié)果:
WebForm1.aspx----------if(a=="")
WebForm2.aspx-------if(a==String.Empty)
WebForm3.aspx-------if(a.Length==0)
所以3種方法量化的結(jié)果是98,105,168:
| 方法 | 結(jié)果 |
| if(a=="") | 98 |
| if(a==String.Empty) | 105 |
| if(a.Length==0) | 168 |
那么為什么if(a.Length==0)最快呢?
因?yàn)檎麛?shù)判斷等于最快,沒有經(jīng)過實(shí)例化等復(fù)雜的過程。
所以:建議大家判斷字符串是否為空用?if(a.Length==0)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/gc2013/p/3924455.html
總結(jié)
以上是生活随笔為你收集整理的C#中判断空字符串的3种方法性能分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【JavaScript】理解与使用Jav
- 下一篇: C#中要使一个类支持FOREACH遍历,