1

I have a simple if in a hot member accessed from multiple threads.

if (boolFlag)
{
    Interlocked.Decrement(ref SomeCount);
}

If C++ were to remove this if case, we would probably multiply reference by flag to get null ptr or actual reference.

Is there some optimisation that would allow similar thing it C#?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DuckQueen
  • 772
  • 10
  • 62
  • 134
  • No. The JIT Compiler might be able to perform such optimizations in some cases, but not in this as `Interlocked.Decrement` cannot handle a null pointer. – Klaus Gütter Nov 15 '22 at 17:30
  • So one idea would be to use a Counter modifier thread in combination with `ConcurrentBag.Add(boolFlag)` in the hot path... Bot would such add actually be faster than if test? – DuckQueen Nov 15 '22 at 17:50
  • Most probably the if will be faster than any such complex constructs. If it really matters: implement both and then measure. – Klaus Gütter Nov 15 '22 at 17:53
  • @DuckQueen forget about the `ConcurrentBag` class. It's a [very specialized](https://stackoverflow.com/questions/15400133/when-to-use-blockingcollection-and-when-concurrentbag-instead-of-listt/64823123#64823123) collection. It's unlikely that you'll find a good use for this class, ever. – Theodor Zoulias Nov 15 '22 at 18:28

0 Answers0