C#空字符串判断性能

C#空字符串判断性能

印象里面Length会统计字符串长度会比较慢!但是没想到是Length比较块!丢脸了!

    #region --空字符串判断最快测试--
    /// <summary>
    /// 空字符串判断最快测试
    /// </summary>
    public class FastCheckEmptyString
    {
        /// <summary>
        /// 空字符串判断最快测试
        /// </summary>
        public static void Run()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 20000; i++)
            {
                sb.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
            }
            string str = sb.ToString();
            System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
            st.Start();
            for (int i = 0; i < 100000000; i++)
            {
                if (str == "")
                { }
            }
            st.Stop();
            Console.WriteLine("str == "" : " + st.ElapsedMilliseconds);
            st.Restart();
            //st.Start();
            for (int i = 0; i < 100000000; i++)
            {
                if (str == String.Empty)
                { }
            }
            st.Stop();
            Console.WriteLine("str == String.Empty : " + st.ElapsedMilliseconds);
            //st = new System.Diagnostics.Stopwatch();
            st.Restart();
            //st.Start();
            for (int i = 0; i < 100000000; i++)
            {
                if (str.Length == 0)
                { }
            }
            st.Stop();
            Console.WriteLine("str.Length == 0 : " + st.ElapsedMilliseconds);
            st.Restart();
            //st.Start();
            for (int i = 0; i < 100000000; i++)
            {
                if (!string.IsNullOrEmpty(str))
                { }
            }
            st.Stop();
            Console.WriteLine("!string.IsNullOrEmpty(str) : " + st.ElapsedMilliseconds);
            //end
        }
    }
    #endregion

测试结果采样:

str == “” : 495
str == String.Empty : 413
str.Length == 0 : 343
!string.IsNullOrEmpty(str) : 317

IsNullOrEmpty()  王者!,其次是Length,其他两种都稍差!

话说回来!还是优化  结构 和 其他缓慢点,优化算法才是王道!  优化这个 性价比不高!

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » C#空字符串判断性能