Also talk about string. isnullorempty

Source: Internet
Author: User
Today, when browsing the devtopics blog, I found an article about string, which describes how to compare a method of string with an attribute when determining whether a string variable is null, to give a string variable's, which of the following expressions is faster?

1. String. isnullorempty (s)
2. S = NULL | S. Length = 0

If you guess the second one, you are right. It will be 15% faster than the string. isnullorempty method, but this is measured in one second per million!
Here is a simple example to compare two methods: 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 ();
}
}
}
The result is as follows:
(String. isnullorempty (s): Time = 00:00:06. 8437500 empties = 50000000
(S = NULL | S. Length = 0): Time = 00:00:05. 9218750 empties = 50000000

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.