Speed difference if var set as global vs being passed on each call??

 

I have two options for my code and was wondering if I was correct in assuming the first option would be more efficient but I'm not sure why I don't see it more often, any thoughts? Is there a problem with this approach, does it make a difference? Thanks

Option 1 (Index is set as a global variable so doesn't need to be passed with the function call):

int Index;
void My_function() {
        Print(Index);
}
for (Index = 0; Index < 100000; Index++) {
        My_function();
}

Option 2 (Index is set by the for loop so needs to be passed with the function call):

void My_function(int Index) {
        Print(Index);
}
for (int Index = 0; Index < 100000; Index++) {
        My_function(Index);
}
 
Enrique Dangeroux #:
Measure https://www.mql5.com/ru/code/31279
I tried measuring and couldn't see a difference, not sure I did it correctly though... maybe they are supposed to come out with the same results in theory. Thanks for the tip.
 
Jeepack:

I have two options for my code and was wondering if I was correct in assuming the first option would be more efficient but I'm not sure why I don't see it more often, any thoughts? Is there a problem with this approach, does it make a difference? Thanks

Option 1 (Index is set as a global variable so doesn't need to be passed with the function call):

Option 2 (Index is set by the for loop so needs to be passed with the function call):

Most compilers (for any language, and I doubt MQL is any exception) do at least basic optimizations while compiling such that whatever you write in your code, the compiler will rewrite it in the most efficient way.  Of course for any given piece of code that process can be easy or hard for the compiler, and one compiler will go to different lengths to optimize more, or less, than another.

I would wager your example is a fairly straight forward one for the compiler, so regardless of which one you write, the resulting binary compiled code will be the same, having optimized one version into the other, or both versions into something else.

All that said, this is only general knowledge of how compilers work in principle. I know nothing of MQLs internals to comment specifically on that. So just making best guesses here.  Certainly if you try it both ways and the performance results are the same then that would support what I'm suggesting. 😊