Doubt about performance in using the using statement

3

Which of the two ways to check if a record of such TYPE has already been registered is more performative? Are there differences, mistakes? What are the implications? Does using block only release connection resources or all objects created in its scope? Does the memory used by using have GC priority? Is there another better way to do this?

Block 1

int valorDoTipo = 5;
Tipo tipo;

using (Contexto contexto = new Contexto())
{
    tipo = contexto.Tipo.FirstOrDefault(t => t.ValorDoTipo == valorDoTipo);
}

if (tipo != null)
    return true;
else
    return false;

Block 2

using (Contexto contexto = new Contexto())
{
    int valorDoTipo = 5;
    Tipo tipo;        
    tipo = contexto.Tipo.FirstOrDefault(t => t.ValorDoTipo == valorDoTipo);
    if (tipo != null)
        return true;
    else
        return false;
}
    
asked by anonymous 04.06.2014 / 17:40

1 answer

3

It has better and more performative solutions than you gave me in your question, one of them just below:

Explanation: How do you want a return (true ou false) would be the best form there, do not need to return a Tipo like the question.

bool retorno = false;
using (Contexto contexto = new Contexto())
{                 
    retorno = contexto.Tipo.Any(t => t.ValorDoTipo == 5);    
}
return retorno;

or

bool retorno = false;
using (Contexto contexto = new Contexto())
{                 
    retorno = contexto.Tipo.AsNoTracking().Any(t => t.ValorDoTipo == 5);    
}
return retorno;

The AsNoTracking() means that it will execute an SQL command on your database and will not attach to its context, ie it increases the performance of the command. Such a command is very used in research, where the intention is only to bring information ( ReadOnly ).

Note: There are two equal (==) in the given comparison seen in the question tag

References:

04.06.2014 / 18:12