I recently saw a question. I want to convert a string [] to an int [] (of course, all numbers are stored in string []), and then I wrote a smallProgramAfter playing the game, four methods are used, but the advantages and disadvantages of the methods are not so obvious:
Static Void Main ( String [] ARGs)
{
// Test string
Stringbuilder test;
String [] STR;
For ( Int J = 0 ; J < 6 ; J ++ )
{
Test = New Stringbuilder ();
For ( Int I = 1 ; I <= ( Int ) Math. Pow ( 10 , J + 1 ); I ++ )
{
Test. append (I + " , " );
}
Test. append ( " 1 " );
Console. writeline ( " The number of elements is " + ( Int ) Math. Pow ( 10 , J + 1 ) + " : " );
Str = Test. tostring (). Split ( ' , ' );
Stringtoint (STR );
Stringtointbylinq (STR );
Stringtointbyarr (STR );
Stringtointbylist (STR );
Console. writeline ();
}
Console. Read ();
}
// The simplest method is loop.
Public Static Void Stringtoint ( String [] Str)
{
Long T1 = Datetime. Now. ticks;
Int [] Intarr = New Int [Str. Length];
For ( Int I = 0 ; I < Str. length; I ++ )
{
Intarr [I] = Convert. toint32 (STR [I]);
}
Console. writeline ( " Loop cost time: " + (Datetime. Now. ticks - T1 ));
}
// Use
Public Static Void Stringtointbylinq ( String [] Str)
{
Long T1 = Datetime. Now. ticks;
Int [] Intarr = Str. Select (o => Convert. toint32 (O). toarray < Int > ();
Console. writeline ( " LINQ cost time: " + (Datetime. Now. ticks - T1 ));
}
// Use the array Conversion Method in. net
Public Static Void Stringtointbyarr ( String [] Str)
{
Long T1 = Datetime. Now. ticks;
Int [] Intarr = Array. convertall < String , Int > (STR, convert. toint32 );
Console. writeline ( " Arr cost time: " + (Datetime. Now. ticks - T1 ));
}
// Generic
Public Static Void Stringtointbylist ( String [] Str)
{
Long T1 = Datetime. Now. ticks;
Int [] Intlist = Str. tolist < String > (). Convertall < Int > (Convert. toint32). toarray < Int > ();
Console. writeline ( " List cost time: " + (Datetime. Now. ticks - T1 ));
}
After running:
The number of elements is 10:
Loop cost time: 0
LINQ cost time: 0
Arr cost time: 0
List cost time: 0
The number of elements is 100:
Loop cost time: 0
LINQ cost time: 0
Arr cost time: 0
List cost time: 0
The number of elements is 1000:
Loop cost time: 0
LINQ cost time: 0
Arr cost time: 0
List cost time: 0
The number of elements is 10000:
Loop cost time: 0
LINQ cost time: 156000
Arr cost time: 0
List cost time: 0
The number of elements is 100000:
Loop cost time: 468001
LINQ cost time: 468001
Arr cost time: 468001
List cost time: 312000
The number of elements is 1000000:
Loop cost time: 2496004
LINQ cost time: 2808005
Arr cost time: 2184004
List cost time: 2340004
If you have any good methods, let me learn!