Loading
PauloHDSousa - Desenvolvedor: .Net - IsNotNullOrEmpty é mais rápido que IsNullOrEmpty

segunda-feira, 14 de abril de 2014

.Net - IsNotNullOrEmpty é mais rápido que IsNullOrEmpty





Diariamente temos a necessidade de verificar se uma STRING  não é nula nem vazia para executarmos um código e geralmente fazemos o que está no código B.

!IsNullOrEmpty(string)

Pois saiba que um código que verifica se uma string não é nula ou não é vazia é muito mais rápido do que verificar se ela é nula ou vazia e depois negar o retorno. 

IsNotNullOrEmpty é mais rápido do que !IsNullOrEmpty

Não é uma diferença perceptível mas fica aí a curiosidade.

using System;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace N {
    class P {
        static void Main(string[]a){

            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 < 99999999; i++)
                t1 = IsNotNullOrEmpty(teste);
            sw1.Stop();


            //B
            sw2.Start();
            bool t2;
            for (int p = 0; p < 99999999; p++)
                t2 = !IsNullOrEmpty(teste);
            sw2.Stop();

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

        public static bool IsNotNullOrEmpty(String value) {
            return (value != null || value.Length != 0);
        }

        public static bool IsNullOrEmpty(String value) {
            return (value == null || value.Length == 0);
        }
    }
}

Nenhum comentário: