IsNullOrEmpty and S = = NULL | | S.length = 0 which is fast

Source: Internet
Author: User
Tags datetime

Describes the comparison between a method of a string and a property to determine whether a string variable is empty, a string variable ' s ', and the following expression is faster?

1. String.IsNullOrEmpty (s)

2. S = = NULL | | s.length = 0

If you guess the second one, then you're right. It will be 15% faster than the String.IsNullOrEmpty method, but this is measured in one out of 10,000 seconds!

Here's a simple example to compare 2 different ways:

Using System;

Namespace Stringnullempty

{

Class Program

{

static void Main (string[] args)

{

Long loop = 100000000;

string s = null;

Long option = 0;

Long empties1 = 0;

Long empties2 = 0;

DateTime time1 = DateTime.Now;

for (long i = 0; I < loop; i++)

{

option = i% 4;

Switch (option)

{

Case 0:

s = null;

Break

Case 1:

s = String.Empty;

Break

Case 2:

s = "H";

Break

Case 3:

s = "HI";

Break

}

if (String.IsNullOrEmpty (s))

empties1++;

}

DateTime time2 = DateTime.Now;

for (long i = 0; I < loop; i++)

{

option = i% 4;

Switch (option)

{

Case 0:

s = null;

Break

Case 1:

s = String.Empty;

Break

Case 2:

s = "H";

Break

Case 3:

s = "HI";

Break

}

if (s = = NULL | | s.length = 0)

empties2++;

}

DateTime Time3 = DateTime.Now;

TimeSpan span1 = time2. Subtract (time1);

TimeSpan span2 = Time3. Subtract (time2);

Console.WriteLine ("(String.IsNullOrEmpty (s)): time={0} empties={1}",

Span1, empties1);

Console.WriteLine ("(s = = NULL | | S.length = = 0): time={0} empties={1} ",

Span2, Empties2);

Console.ReadLine ();

}

}

}

Here is the result:

(String.IsNullOrEmpty (s)): time=00:00:06.8437500 empties=50000000

(s = = NULL | | s.length = 0): time=00:00:05.9218750 empties=50000000

---------------------------------------------------------------------------------------------

It can be seen that string.isnullorempty although slow to run, but it is easy to read, Microsoft's design is still very humane ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.