Loading
PauloHDSousa - Desenvolvedor: Qual código é mais rápido? A ou B

quinta-feira, 20 de março de 2014

Qual código é mais rápido? A ou B



 Código A:

t1 = teste == null || teste.Length == 0;

Código B:

t2 = teste == null || teste == "";


Qual é mais rápido?

 


            string teste = "O Rato roeu a roupa do rei de roma";
            Stopwatch sw1 = new Stopwatch();
            Stopwatch sw2 = new Stopwatch();

            //A
            sw1.Start();
            bool t1;
            for (int i = 0; i < 999999999; i++)
                t1 = teste == null || teste.Length == 0;
            sw1.Stop();


            //B
            sw2.Start();
            bool t2;
            for (int p = 0; p < 999999999; p++)
                t2 = teste == null || teste == "";
            sw2.Stop();

            TimeSpan ts1 = sw1.Elapsed;
            TimeSpan ts2 = sw2.Elapsed;

Resposta:Código A

Qual é mais rápido?



             string teste = "O Rato roeu a roupa do rei de roma";

            Stopwatch sw1 = new Stopwatch();

            Stopwatch sw2 = new Stopwatch();

            //A
            sw1.Start();
            bool t1;
            for (int i = 0; i < 9999999; i++)
                t1 = teste == null || teste.Count() == 0;
            sw1.Stop();
           
            //B
            sw2.Start();
            bool t2;
            for (int p = 0; p < 9999999; p++)
                t2 = teste == null || teste.Length == 0;
            sw2.Stop();

            TimeSpan ts1 = sw1.Elapsed;
            TimeSpan ts2 = sw2.Elapsed;

 Resposta:Código B (usando Length)

Nenhum comentário: