Multiple methods for determining whether a string is full of numbers and their performance comparison (C # implementation)

Source: Internet
Author: User

Public static bool isnumber (string checknumber)
{
Bool ischeck = true;

If (string. isnullorempty (checknumber ))
{
Ischeck = false;
}
Else
{
Char [] charnumber = checknumber. tochararray ();

For (INT I = 0; I <charnumber. length; I ++)
{
If (! Char. isnumber (charnumber [I])
{
Ischeck = false;
Break;
}
}
}

Return ischeck;
}

During programming, it is often necessary to determine whether all the characters in a string are digits (0-9). This is a very easy function,ProgramThe first thing people will think of is, is there any ready-made function that can be used for such a simple function? VB.. Net has an isnumeric (object). in C #, only the char of a single character is judged. isnumber () and isnumeric can be used to determine the double-type numeric string, but they cannot be used to exclude the plus and minus signs and decimal points. If they are used to determine whether the string is a number, however, it cannot be used to determine whether a string is composed of digits. There is no ready-made method, so I have to write the function myself:

Public static bool isnum (string Str)
{
For (INT I = 0; I <Str. length; I ++)
{
If (! Char. isnumber (STR, I ))
Return false;
}
Return true;
}

Or use a regular expression: "^ \ D + $"

You can also use the exception thrown by int32.parse () to judge:

Try
{
Int32.parse (tobetested );
}
Catch
{
// If an exception occurs, it is not a number.
}

Which method is the best? Each has its own advantages and disadvantages. I wrote a program to test the time required for each method. The main () content of the test program is as follows:

RegEx isnumeric = new RegEx (@ "^ \ D + $ ");
Int times = 10000000;
Int start, end;
Int I;
String tobetested = "6741 s ";

# Region test User Function
Start = system. environment. tickcount;
For (I = 0; I <times; I ++)
{
Timingtest. isnum (tobetested );
}
End = system. environment. tickcount;
Console. writeline ("User Function time:" + (end-Start)/1000.0 + "seconds ");
# Endregion

# Region test Regular Expression
Start = system. environment. tickcount;
For (I = 0; I <times; I ++)
{
Isnumeric. ismatch (tobetested );
}
End = system. environment. tickcount;
Console. writeline ("Regular Expression time:" + (end-Start)/1000.0 + "seconds ");
# Endregion

# Region test exception
Start = system. environment. tickcount;
For (I = 0; I <times/100; I ++)
{
Try
{
Int32.parse (tobetested );
}
Catch
{
// If an exception occurs, it is not a number.
}

}
End = system. environment. tickcount;
Console. writeline ("exception time:" + (end-Start)/10.0 + "seconds ");
# Endregion

# Region test VB. NET isnumeric ()
Start = system. environment. tickcount;
For (I = 0; I <times/10; I ++)
{
Microsoft. VisualBasic. Information. isnumeric (tobetested );
}
End = system. environment. tickcount;
Console. writeline ("VB. NET isnumeric () Time:" + (end-Start)/100.0 + "seconds ");
# Endregion

Because the exception takes too long, only 1/100 is tested. This is not rigorous, but the order of magnitude is correct.

The result of three operations is:
User Function time: 1.938 seconds
Regular Expression time: 11.921 seconds
Exception time: 600 seconds
VB. NET isnumeric () Time: 40.797 seconds
User Function time: 1.953 seconds
Regular Expression time: 12.016 seconds
Exception time: 590.6 seconds
VB. NET isnumeric () Time: 40 seconds
User Function time: 2.000 seconds
Regular Expression time: 12 seconds
Exception time: 595.3 seconds
VB. NET isnumeric () Time: 39.69 seconds
Average time:

1.964
11.979
595.3
40.162

The speed ratio is about:303: 49.7: 1: 14.82

The result is obvious: the user-defined function is the fastest, and the exception is the slowest. If no exception is required, string tobetested = "67412"; the result is:

User Function time: 1.922 seconds
Regular Expression time: 9.64 seconds
Exception time: 3.1 seconds
VB. NET isnumeric () Time: 39.07 seconds
The speed ratio is about:20.33: 4.05: 12.60: 1

Conclusion:

User-defined functions provide maximum flexibility and performance, and are not complex.
The Regular Expression and isnumeric speed are on the same order of magnitude, but the regular expression can determine a string format, such as specifying that there must be or no decimal point, and isnumeric cannot.
Exceptions should be avoided.We recommend that you only use exception as a means to handle exceptions, rather than as a means to control the process.The test also shows that a large amount of resources is required when an exception is thrown.
Isnumeric is a ready-made function, which is the most convenient to use. It can only determine whether the given parameter is a value (Boolean/byte/int16/int32/int64/single/double/decimal ), further requirements cannot be made (whether there are decimal points or not ). However, the isnumeric parameter is an object, not limited to string.

I can't help but wonder if there are any faster methods than user-defined functions? The answer is yes. In the previous user-defined function, char is used. isnumber () function. This function can not only judge '1' in the standard ASCII code, but also true for '1' in full-width Chinese. It can be seen that char. isnumber () determines the numbers in all Unicode characters, and numbers in other languages are also included. If we only allow '1' in ASCII, we can change it as follows:

Public static bool isnum (string Str)
{
For (INT I = 0; I <Str. length; I ++)
{
If (STR [I] <= '0' | STR [I]> = '9 ')
Return false;
}
Return true;
}

I was surprised by the test results, which is faster than the original isnum.10Times, the average execution time is0.205Seconds!

The results have all come out, and you must know how to choose them. I don't need to talk about anything.

Happy New Year!

 

Related Article

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.