Hello all,
First of all, sorry if this is kind of a dumb question, but I can't seem to find an answer for it.
Let's say that in a c# project (in my case, a c# script inside a Unity3d game, if that changes something), I have two methods defined as follows (in pseudo code):
int x;
int y;
​int z;
​int u;
​int v; // these ints are given values depending on the evolution of each game run, so they are not known at compile time.
bool intToBool( int x ) { /*some complex block that computes a bool from the passed argument*/}
int gdc ( int x ) { /* method that takes a int value dependent on the game run
-that is, not known at compile time-
and computes another int from it thorugh very complex and expensive calculations*/}
void SomeStuff(int x){} //auxiliar methods called inside myMethod
void OtherStuff(int x){}
void MoreStuff(int x){}
void myMethod(int a, int b, int c, int d, int e){
/* here goes code that references the arguments by name multiple name, for example:*/
SomeStuff(a); OtherStuff(b); MoreStuff(c);
SomeStuff(d); OtherStuff(e); MoreStuff(a);
SomeStuff(b); OtherStuff(c); MoreStuff(d);
SomeStuff(e); OtherStuff(a); MoreStuff(b);
SomeStuff(c); OtherStuff(d); MoreStuff(e);
}
void myMethodBis(int a, int b, int c, int d, int e){
if( intToBool( a )) { /*execute statemens*/ }
else if( intToBool( b )) { /*execute statemens*/ }
else if( intToBool( x )) { /*execute statemens*/ }
else if( intToBool( d )) { /*execute statemens*/ }
else if( intToBool( e )) { /*execute statemens*/ }
}
Further suppose that these methods are going to be called with arguments that are not known at compile time (e.g. because they depend on the evolution of the particular run on the game), like this:
myMethod( gdc(x), gdc(y), gdc(z), gdc(u), gdc(v) );
myMethodBis( gdc(x), gdc(y), gdc(z), gdc(u), gdc(v) );
So, my question is, when are gdc(x)-gdc(v), etc. evaluated?
Are they first computed at the start of the method calls and saved as local variables internally?
Or are they computed each time they are referenced in the method's block?
So, for example, if gdc(x) - gdc(v) are going to be computed regardless of wether they are called in the method's body, and gdc is very computationally intensive, I should rather inline MyMethodBis to save four of these computation.
On the other hand, if they are computed not when the method is invoked but when they are used inside the method body, In myMethod I should first save a-e as local variables so I'm only computing them once, and use the local variables several times through the method's body.
(Bear in mind that the main aim of my question is to know how is the code executed internally, rather than having to do the optimisations I meantion. That has been only the problem that has sparkled the theoretical question).
Thank you in advance for any insight you can give regarding this topic.