string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

后端 未结 9 712
广开言路
广开言路 2020-11-28 03:02

Is use of string.IsNullOrEmpty(string) when checking a string considered as bad practice when there is string.IsNullOrWhiteSpace(string) in .NET 4.

9条回答
  •  [愿得一人]
    2020-11-28 03:17

    Check this out with IsNullOrEmpty and IsNullOrwhiteSpace

    string sTestes = "I like sweat peaches";
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < 5000000; i++)
        {
            for (int z = 0; z < 500; z++)
            {
                var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
            }
        }
    
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;
        // Format and display the TimeSpan value. 
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
        Console.ReadLine();
    

    You'll see that IsNullOrWhiteSpace is much slower :/

提交回复
热议问题