I'm using an API where, unfortunately, calling a get property accessor has a side-effect. How can I ensure that:
public void Foo()
{
var x = obj.TheProp; // is it guarnateed to be accessed?
}
isn't optimized away by the compiler?
(transitive, programming) To omit (some portion of program logic) through optimization, when it is found to be unused or unnecessary.
We say that code optimization is writing or rewriting code so a program uses the least possible memory or disk space, minimizes its CPU time or network bandwidth, or makes the best use of additional cores. In practice, we sometimes default to another definition: Writing less code.
The first step in optimizing a program is to eliminate unnecessary work, making the code perform its in- tended task as efficiently as possible. This includes eliminating unnecessary function calls, conditional tests, and memory references.
That will not be optimized away - the getter is a method and will be invoked, although the JIT might choose to "inline" a lot of it if it is simple, perhaps eventually (and entirely theoretically) ending up with just a null-reference check if TheProp
doesn't do anything particularly exciting. What can happen is that the "thing returned" (that the code stores into x
) is eligible for garbage collection before the method ends; this is rarely an issue, except with things like an out-of-process mutex; in which case, you can do things like:
var x = obj.TheProp;
// long-running code here
GC.KeepAlive(x);
Note, however, that if x
is value-typed, this will force it to be boxed, which is not ideal.
Emphasis, though: the above is not intended to ensure that TheProp
is actually invoked; it is for a specific set of garbage-related scenarios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With