Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure statement is not optimized "away"

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?

like image 413
D.R. Avatar asked Oct 13 '14 14:10

D.R.


People also ask

What does optimized out mean?

(transitive, programming) To omit (some portion of program logic) through optimization, when it is found to be unused or unnecessary.

What does it mean to optimize your code?

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.

How do I optimize my program performance?

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.


1 Answers

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.

like image 188
Marc Gravell Avatar answered Oct 08 '22 16:10

Marc Gravell