Pergunta

If I am comparing two known value types, will I get better performance from the | or || operator in c#?

My particular use case is a bool member in the class indicating stale data, being activated by a loop method like this:

private bool _stale;
private HashSet<Foo> _foos;

Then another method loops and possibly activates this flag

foreach (var foo in foos)
{
    _stale = _foos.Add(foo) | _stale;

    //Or is the following line better?
    //_stale = _foos.Add(foo) || _stale; 
}

I suppose I'm asking if the overhead of the short-circuiting operator is enough that I wouldn't use it for checking against an already assigned value type...

Foi útil?

Solução

I would use the Or Assignment operator:

_stale |= added;

Or:

_stale |= _foos.Add(foo);

This operator is specifically designed for this purpose, which makes the intent clear (and will most likely be the best in terms of performance, as it's specifically designed for this purpose).

As for the actual performance, this level of micro-optimization is typically almost impossible to measure as any difference in performance is going to be so much smaller than the difference in your operations (the HashSet<T>.Add call) that clarity of code is far more important. You could build a test to measure this, but it is incredibly unlikely to be reliably different enough in terms of performance to matter.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top