关于字符串为空的几个性能测试

发表于:2018-6-19 17:17

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:一方乐土    来源:博客园

分享:
  测试程序如下:
  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),我们将立即处理。
22/2<12
价值398元的测试课程免费赠送,填问卷领取吧!

精彩评论

  • bling123
    2018-6-21 16:15:36

    嗯、收藏了

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2022
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号