GML [ANSWERED] how to use 'for' loops & arrays)

G

Guest User

Guest
hi yall, i've always gone through arrays like this:
Code:
for(var i = 0; i < n; i++) { Array[@ i] = -1; }
however, upon reading this thread am i understanding correctly that this is more efficient:
Code:
for(var i = 0; i < n; ++i) { Array[@ i] = -1; }
?

this is how i do my menus, or at least the part where it draws all the options:
Code:
#event draw_gui

    var _ArrayOptions = [ "Continue", "New Game", "Settings", "Credits", "Exit" ];
    for(var i = 0; i < 4; i++) {
        if(i != menu_cursor) { draw_text_grid(2, 3 + i, _ArrayOptions[i]); } }
    draw_text_grid(2, 3 + menu_cursor, _ArrayOptions[menu_cursor], global.GUIcolor);
so i'm wondering a few things:
1) is there a difference between i++ and ++i in this case, then?
2) i am aware that it's more efficient to initialize an array backwards, but if there is differences in increment/decrement operator in for loops, then is there a difference in efficiency for going backwards through an array v. going forwards as well just to access their data as i am doing here?

this is, of course, all assuming that the way i am using for loops and arrays here for my menus is acceptable in the first place. if this is poor method i would also appreciate being informed of that too.

thanks
 

jo-thijs

Member
hi yall, i've always gone through arrays like this:
Code:
for(var i = 0; i < n; i++) { Array[@ i] = -1; }
however, upon reading this thread am i understanding correctly that this is more efficient:
Code:
for(var i = 0; i < n; ++i) { Array[@ i] = -1; }
?
It depends on the quality of the compiler (and I'm guessing the compilers GameMaker use are optimized enough for this).
However, even if the latter would be more efficient, it would only save you 1 subtraction per iteration, which is negligable.

1) is there a difference between i++ and ++i in this case, then?
In your case, no.

2) i am aware that it's more efficient to initialize an array backwards, but if there is differences in increment/decrement operator in for loops, then is there a difference in efficiency for going backwards through an array v. going forwards as well just to access their data as i am doing here?
Yes actually.
Looping backwards through arrays may result in more cache misses.
This may result in worse performance when looping over an array backwards.
However, this is negligable again.

You can generally (always in GameMaker) assume looping forwards or backwards over an array will ave the same performance.

this is, of course, all assuming that the way i am using for loops and arrays here for my menus is acceptable in the first place. if this is poor method i would also appreciate being informed of that too.
I don't see anything bad about that.
 
Top