by agnaldo
23. março 2011 10:31
Como expliquei no post que fiz comparando métodos que retornem um literal, usem loop e um recursivo, existe uma grande diferença de desempenho...
Mas não é só quanto à escolha da estratégia de cálculo... a escolha do tipo também é relevante. Para números inteiros, o processador tem uma "preferência" por números int, ou seja, cálculos com int são mais performáticos que cálculos com outros formatos inteiros.
Para demonstrar esse comportamento fiz um programinha que executou 400.000.000 de operações com números do tipo short, int e long e o resultado (com alguma flutuação, claro) foi:

Criei uma aplicação console cujo código está abaixo:
using System;
using System.Diagnostics;
namespace Cliente
{
class Program
{
static void Main(string[] args)
{
long tempoInt16 = 0, tempoInt32 = 0, tempoInt64 = 0;
int qtd = 20000;
short totalShort = 0;
int totalInt = 0;
long totalLong = 0;
Stopwatch s = new Stopwatch();
s.Start();
for (int x = 0; x < qtd; x++)
for (short i = 0; i < qtd; i++)
totalShort = Somar(i);
s.Stop();
Console.WriteLine("short: {0} ms",
tempoInt16 = s.ElapsedMilliseconds);
s.Reset();
s.Start();
for (int x = 0; x < qtd; x++)
for (int i = 0; i < qtd; i++)
totalInt = Somar(i);
s.Stop();
Console.WriteLine("int..: {0} ms",
tempoInt32 = s.ElapsedMilliseconds);
s.Reset();
s.Start();
for (int x = 0; x < qtd; x++)
for (long i = 0; i < qtd; i++)
totalLong = Somar(i);
s.Stop();
Console.WriteLine("long.: {0} ms",
tempoInt64 = s.ElapsedMilliseconds);
Console.WriteLine();
Console.WriteLine("short x int......: {0:n2} %",
(tempoInt16 - tempoInt32) * 100.0 / tempoInt32);
Console.WriteLine("long x int......: {0:n2} %",
(tempoInt64 - tempoInt32) * 100.0 / tempoInt32);
Console.ReadKey();
}
private static short Somar(short x)
{
return (short)(x + x);
}
private static int Somar(int x)
{
return x + x;
}
private static long Somar(long x)
{
return x + x;
}
}
}