C# 判断字符串为Null或空的方法

判断字符串为Null或空的方法

  1. IsNullOrEmpty
  2. p == null || p == “”
  3. p == null && p.Length == 0: 861ms
  4. (p +”“).Length == 0: 1050ms

测试结果

测试1
- IsNullOrEmpty: 943ms
- p == null || p == “”: 1093ms
- p == null || p.Length == 0: 831ms
- (p +”“).Length == 0: 1115ms
测试2
- IsNullOrEmpty: 850ms
- p == null || p == “”: 1005ms
- p == null || p.Length == 0: 847ms
- (p +”“).Length == 0: 1077ms

结论

  1. p == null || p.Length == 0 最快
  2. IsNullOrEmpty与p == null || p.Length == 0 差距很小。
  3. 3.

Code

 var sw = new System.Diagnostics.Stopwatch();
            var p = default(string);
            var q = "";
            var r = "str";

            sw.Reset();
            sw.Start();
            for (var i = 1; i < 100000000; i++)
            {
                var pR = string.IsNullOrEmpty(p);
                var qR = string.IsNullOrEmpty(q);
                var rR = string.IsNullOrEmpty(r);
            }

            sw.Stop();
            Console.WriteLine("IsNullOrEmpty: " + sw.ElapsedMilliseconds.ToString() + "ms");

            sw.Reset();
            sw.Start();
            for (var total = 1; total < 100000000; total++)
            {
                var pR = p == null || p == "";
                var qR = q == null || q == "";
                var rR = r == null || r == "";
            }

            sw.Stop();
            Console.WriteLine("p == null || p == \"\": " + sw.ElapsedMilliseconds.ToString() + "ms");

            sw.Reset();
            sw.Start();
            for (var total = 1; total < 100000000; total++)
            {
                var pR = p == null || p.Length == 0;
                var qR = q == null || q.Length == 0;
                var rR = r == null || r.Length == 0;
            }

            sw.Stop();
            Console.WriteLine("p == null || p.Length == 0: " + sw.ElapsedMilliseconds.ToString() + "ms");

            sw.Reset();
            sw.Start();
            for (var total = 1; total < 100000000; total++)
            {
                var pR = (p +"").Length == 0;
                var qR = (q +"").Length == 0;
                var rR = (r +"").Length == 0;
            }

            sw.Stop();
            Console.WriteLine("(p +\"\").Length == 0: " + sw.ElapsedMilliseconds.ToString() + "ms");

你可能感兴趣的:(C#)