测试程序如下:
using System; using System.Collections.Generic; using System.Text; namespace testEmpty { class Program { static void Main(string[] args) { Test test = new Test(); test.test1(); test.test2(); test.test3(); test.test4(); test.test5(); Console.Read(); } } class Test { string str = string.Empty; public void test1() { for (int i = 0; i < 10000; i++) { if (str == "") { Console.WriteLine("1 This string is emput"); } } } public void test2() { for (int i = 0; i < 10000; i++) { if (str.Equals("")) { Console.WriteLine("2 This string is emput"); } } } public void test3() { for (int i = 0; i < 10000; i++) { if (str==string.Empty) { Console.WriteLine("3 This string is emput"); } } } public void test4() { for (int i = 0; i < 10000; i++) { if (str.Equals(string.Empty)) { Console.WriteLine("4 This string is emput"); } } } public void test5() { for (int i = 0; i < 10000; i++) { if (str .Length==0) { Console.WriteLine("5 This string is emput"); } } } } } |
在这个测试程序中,用了5个分别含有这5种判断语句的方法,目的就是为了测试每个方法耗费的时间。
在这里说明一下,笔者在这个程序中起的名字不可取,程序员不应该这样为方法起名字的,见笑了!
测试结果如下:
可以从这个方法耗费时间详细说明表中看出,这些方法耗费时间都比较,这主要是因为里面的Console.WriteLine()语句影响的。但是每个方法中都有这一语句,所以说它并不影响我们的比较结果!
得出的结论:在字符串为空时,这五种判断语句的耗费时间由短到长
str .Length==0 str.Equals("") str==string.Empty str.Equals(string.Empty) str == "" |
需要说明的是:这只是在字符串为空时结果是这样的,那么字符串不为空时呢,结果又是怎样的呢?
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。