2011-01-21 13 views

risposta

7

Se sai che stai andando ad essere la conversione di un string-Int32, utilizzando Convert.ChangeType sembra un modo di fare oscura quella. Sicuramente preferirei le altre chiamate a questo.

La differenza principale tra int.Parse e Convert.ToInt32(x) è che Convert.ToInt32(null) restituisce 0 dove, come int.Parse(null) sarà un'eccezione. Naturalmente, int.Parse ti dà anche più controllo in termini di quale cultura viene utilizzata.

dubito molto che non c'è alcun beneficio delle prestazioni di uno sopra l'altro: vorrei aspetterebbeConvert.ToInt32 per chiamare int.Parse, piuttosto che il contrario - ma non è documentato a lavorare in questo modo, e il colpo di è improbabile che una singola chiamata al metodo sia significativa. (Potrebbe essere comunque in linea.)

+0

Sia Convert.ToInt32() che Int32.Parse() utilizzano il metodo (non disponibile al pubblico) System.Number.ParseInt32() che a sua volta richiama System.Number.StringToNumber(). Come faccio a saperlo? Guarda la traccia dello stack di FormatException che viene generata quando si passa una stringa non valida :-) –

+0

@ user532870: Giusto abbastanza - ma non mi farei mai affidamento su quel genere di cose :) –

+0

@ user532870: Jon ha ragione. reflection indica che Convert.ToInt32 chiama int.Parse che chiama Number.ParseInt32. @ Jon: Quindi int.Parse è migliore? – naveen

0

Sì.

Convert.ToInt32 è meglio che utilizzare Convert.ChangeType per lo stesso scopo.

ChangeType è un metodo di conversione generico che converte l'oggetto specificato dal valore in conversionType. Mentre ToInt32 è specifico per il tipo int32.

+1

Infatti, 'ChangeType()' è programmatico 'cast', nel frattempo' Convert.ToInt32() 'crea veramente' int' da altro tipo – abatishchev

3
private const int maxValue = 1000000; 
    static void Main(string[] args) 
    { 
     string[] strArray = new string[maxValue]; 
     for (int i = 0; i < maxValue; i++) 
     { 
      strArray[i] = i.ToString(); 
     } 
     int[] parsedNums = new int[maxValue]; 
     CalcChangeTypePerf(strArray,parsedNums); 
     CalcToInt32Perf(strArray, parsedNums); 
     CalcIntParse(strArray, parsedNums); 
    } 
    public static void CalcChangeTypePerf(string[] strArray,int[] parsedArray) 
    { 
     Stopwatch stopwatch = new Stopwatch(); 
     stopwatch.Start(); 
     for (int i = 0; i < maxValue; i++) 
     { 
      parsedArray[i] = (int)Convert.ChangeType(strArray[i], typeof(int)); 
     } 
     stopwatch.Stop(); 
     Console.WriteLine("{0} on CalcChangeTypePerf", stopwatch.ElapsedMilliseconds); 
    } 
    public static void CalcToInt32Perf(string[] strArray, int[] parsedArray) 
    { 
     Stopwatch stopwatch = new Stopwatch(); 
     stopwatch.Start(); 
     for (int i = 0; i < maxValue; i++) 
     { 
      parsedArray[i] = Convert.ToInt32(strArray[i]); 
     } 
     stopwatch.Stop(); 
     Console.WriteLine("{0} on CalcToInt32Perf", stopwatch.ElapsedMilliseconds); 
    } 
    public static void CalcIntParse(string[] strArray, int[] parsedArray) 
    { 
     Stopwatch stopwatch = new Stopwatch(); 
     stopwatch.Start(); 
     for (int i = 0; i < maxValue; i++) 
     { 
      parsedArray[i] = int.Parse(strArray[i]); 
     } 
     stopwatch.Stop(); 
     Console.WriteLine("{0} on CalcIntParse", stopwatch.ElapsedMilliseconds); 
    } 

Questo semplice i risultati dei test questa

266 on CalcChangeTypePerf 
167 on CalcToInt32Perf 
165 on CalcIntParse 
+2

Stai creando un milione di oggetti in ogni prova, inutilmente. Mentre ogni test è "uguale" in questo modo, significa che le differenze relative nell'effettivo * tempo di parsing * sono mascherate, e potrebbe esserci una garbage collection all'interno di un test, ripulendo i rifiuti da un altro. Ti suggerisco di creare una serie di stringhe * una volta * all'inizio e riutilizzarla. –

+0

Risolto Jon, hai ragione, i tempi sono davvero diversi ... –

0

prova semplice mostra Parse() è metodo più veloce, la prossima Convert.ToInt32() e ultima Convert.ChangeType():

static void Main(string[] args) 
{ 
    string s = "104563"; 
    int a = 1; 

    for (int k = 0; k < 4; k++) 
    { 
     Stopwatch w = Stopwatch.StartNew(); 
     for (int i = 0; i < 10000000; i++) 
      a = (int)Convert.ChangeType(s, typeof(int)); 
     w.Stop(); 

     Console.WriteLine("ChangeType={0}", w.ElapsedMilliseconds); 

     Stopwatch w1 = Stopwatch.StartNew(); 
     for (int i = 0; i < 10000000; i++) 
      a = Convert.ToInt32(s); 
     w1.Stop(); 

     Console.WriteLine("ToInt32={0}", w1.ElapsedMilliseconds); 

     Stopwatch w2 = Stopwatch.StartNew(); 
     for (int i = 0; i < 10000000; i++) 
      a = Int32.Parse(s); 
     w2.Stop(); 
     Console.WriteLine("Parse={0}", w2.ElapsedMilliseconds); 
    } 

    Console.ReadLine(); 
} 

risultato è:

ChangeType=2422 
ToInt32=1859 
Parse=1760 
ChangeType=2374 
ToInt32=1857 
Parse=1762 
ChangeType=2378 
ToInt32=1860 
Parse=1763 
ChangeType=2375 
ToInt32=1855 
Parse=1759 
Problemi correlati