.net字符串数组查找方式效率比较

下面是代码:

 static void Main(string[] args)
        {
            string[] arr = new string[] { "AAA", "BBBB", "CCCC", "DDDD", "EEEEEE", "ffffff", "ggggggg", "hhhhhh", "iii", "", "jjj", "kkk" };
            string findStr = "kkk";
            for (int i = 0; i < arr.Length; i++)
            {
                if (object.ReferenceEquals(findStr, arr[i]))
                    Console.Write(" true1 ");
            }
            Console.WriteLine();
            Console.Write("input string kkk :");

            string inputStr = Console.ReadLine();

            if (CompareStringInArrar( inputStr, arr))
            {
                Console.WriteLine(" true2 ");
            }
            ///////////////////////
            Console.WriteLine("一千万次字符串数组元素查找:");
            System.Threading.Thread.Sleep(3000);

            long ticks = DateTime.Now.Ticks;
            for (int i = 0; i < 10000000; i++)
            {
                CompareStringInArrar(inputStr, arr);
            }
            Console.WriteLine("自定义数组查找(Ticks):              {0}", DateTime.Now.Ticks - ticks);
            ////////////////////////////////////////
            System.Threading.Thread.Sleep(3000);

            ticks = DateTime.Now.Ticks;
            for (int i = 0; i < 10000000; i++)
            {
                FindStringInArrar0(ref findStr, arr);
            }
            Console.WriteLine("直接对象地址相等进行数组查找(Ticks):{0}", DateTime.Now.Ticks - ticks);
            ///////////////////////////////////
            System.Threading.Thread.Sleep(3000);

            ticks = DateTime.Now.Ticks;
            for (int i = 0; i < 10000000; i++)
            {
                FindStringInArrar(ref inputStr, arr);
            }
            Console.WriteLine("直接遍历进行数组查找(Ticks):        {0}", DateTime.Now.Ticks - ticks);

            ///////////////////////////////////
            System.Threading.Thread.Sleep(3000);

            ticks = DateTime.Now.Ticks;
            for (int i = 0; i < 10000000; i++)
            {
                CompareStringInArrar2( inputStr, arr);
            }
            Console.WriteLine("混合数组查找(Ticks):                {0}", DateTime.Now.Ticks - ticks);

           

           Console.Read();
            //DBMethod();
        }

        private static bool FindStringInArrar0(ref string inputStr, string[] arr)
        {
            for (int j = 0; j < arr.Length; j++)
            {
                if (object.ReferenceEquals(inputStr, arr[j]))
                    return true;
            }
            return false;
        }

        private static bool FindStringInArrar(ref string inputStr, string[] arr)
        {
            for (int j = 0; j < arr.Length; j++)
            {
                if (inputStr == arr[j])
                    return true;
            }
            return false;
        }

        private static bool CompareStringInArrar( string inputStr, string[] arr)
        {
            //char[] inputCharArr = inputStr.ToCharArray();
            int length = inputStr.Length;
            bool flag = true;
            //string strTemp = null;
            for (int i = 0; i < arr.Length; i++)
            {
                //strTemp = arr[i];
                if (length == arr[i].Length)
                {
                    flag = true;
                    for (int j = 0; j < length; j++)
                    {
                        if (inputStr[j] != arr[i][j])
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 混合查找
        /// </summary>
        /// <param name="inputStr"></param>
        /// <param name="arr"></param>
        /// <returns></returns>
        private static bool CompareStringInArrar2(string inputStr, string[] arr)
        {
            //char[] inputCharArr = inputStr.ToCharArray();
            int length = inputStr.Length;
            bool flag = true;
            //string strTemp = null;
            for (int i = 0; i < arr.Length; i++)
            {
                if (object.ReferenceEquals(inputStr, arr[i]))
                    return true;
                //strTemp = arr[i];
                if (length == arr[i].Length)
                {
                    flag = true;
                    for (int j = 0; j < length; j++)
                    {
                        if (inputStr[j] != arr[i][j])
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                        return true;
                }
            }
            return false;
        }

但是通常比较都需要忽略大小写比较,所以不能单纯使用这种方式比较,用下面的测试代码:

class Program
    {
        static void Main(string[] args)
        {
            string A = "124Abc";
            string B = "2345b";
            string C = "124abce";
            Console.WriteLine("input string(123Abc):");
            string D = Console.ReadLine();
            string E = "124Abc";

            long ticks = 0;
            long ticks2 = 0;
            long ticks3 = 0;
            long ticks4 = 0;
            long ticks5 = 0;
            

            Stopwatch sw = Stopwatch.StartNew();
            //预热
            for (int i = 0; i < 1000000; i++)
            {
                bool b1 = string.Compare(A, B, StringComparison.OrdinalIgnoreCase) == 0;
            }
            //开始
            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                bool b1 = string.Compare(A, D, StringComparison.OrdinalIgnoreCase) == 0;
            }
            ticks = sw.ElapsedTicks;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                bool b2 = string.Equals(A, C, StringComparison.OrdinalIgnoreCase);
            }
            ticks2 = sw.ElapsedTicks;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                bool b2 = string.Equals(A, D, StringComparison.OrdinalIgnoreCase);
            }
            ticks3 = sw.ElapsedTicks;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                bool b2 = string.Equals(A, E, StringComparison.OrdinalIgnoreCase);
            }
            ticks4 = sw.ElapsedTicks;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                bool b2 = A.Length== C.Length && string.Equals(A, C, StringComparison.OrdinalIgnoreCase);
            }
            ticks5 = sw.ElapsedTicks;

            Console.WriteLine("{0},\r\n{1},\r\n{2},\r\n{3},\r\n{4}\r\n", ticks, ticks2, ticks3, ticks4, ticks5);
            Console.Read();
        }
    }

最后得出结论,最后一种方式最快,原因在于首先判断了长度,如果不是一样的长度直接跳过比较,下面是测试数据:

input string(123Abc):
123Abc
87806,
15255,
58227,
7569,
1939

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏个人随笔

C#编写影院售票系统(A project with a higher amount of gold )(2:相关代码)

此篇文章为项目代码,,,需要项目需求 ,思路分析与窗体效果请访问:http://www.cnblogs.com/lsy131479/p/8367304.html...

35150
来自专栏飞扬的花生

.net服务器端发起请求封装

17840
来自专栏张善友的专栏

发布一个日期选择控件(ASPNET2.0)

The Coolest DHTML Calendar,这是一个在GPL下发布的JS日历程序,具有极高的可配置性,包括外观样式、显示格式、显示内容等等。默认程序...

33090
来自专栏互联网开发者交流社区

STC-单片机控制系统

22030
来自专栏葡萄城控件技术团队

Table-values parameter(TVP)系列之二: 利用DataTable将其作为参数传给SP

一,回顾         上一部分讲述了“在T-SQL中创建和使用TVP”,通过T-SQL建立如下的对象:         1)Tables ...

23990
来自专栏c#开发者

让web api 4.5支持Jquery.getJson(url,handle)跨域访问

代码片段,google了半天,找到的都是4.5 rc,或之前版本的代码,发现都不能用,正式版后有些方法做了修改。我重新修改一下分享给大家 public stat...

28650
来自专栏跟着阿笨一起玩NET

C#自定义泛型类绑定ComboBox控件

C# WinForm ComboBox 自定义数据项 (ComboBoxItem )

27310
来自专栏菩提树下的杨过

[基础]datagridview绑定数据源的几种常见方式

private void button1_Click(object sender, EventArgs e)         {             /...

26050
来自专栏大内老A

开发自己的Data Access Application Block[下篇]

上接:[原创] 我的ORM: 开发自己的Data Access Application Block - Part I 4. Database 下面来介绍重中之重...

24660
来自专栏互联网开发者交流社区

ORM框架(ITDOS实战源码)

24840

扫码关注云+社区

领取腾讯云代金券