var (local variable) optimal usage

2Dcube

Member
I love the "var" keyword but wonder how it should be used.
For example, I often declare it before using it in a loop:
Code:
var item;
for(var i=0; i<ds_list_size(items); i++)
{
  item = items[| i];
  
  do_something_with(item);
}
But is this necessary? (Actually "i" is not declared before hand so it's inconsistent)

The below is faster to write. Is there a reason not to? The manual didn't seem clear on this but seemed to encourage declaring before a loop.

Code:
for(var i=0; i<ds_list_size(items); i++)
{
  var item = items[| i];
 
  do_something_with(item);
}
Does this reserve a different part of memory each time?

(Does it even make a difference at all?)
 

FrostyCat

Redemption Seeker
In GMS, var declarations are internally merged and pulled up to the top when compiling, so both of your examples work the same way.

A further note: If your code's logic permits it, a better idea to reduce variable usage is to iterate backwards so that the terminating condition can compare to a fixed literal instead of an expression that needs to be evaluated.
Code:
for (var i = ds_list_size(items)-1; i >= 0; i--) {
  do_something_with(items[| i]);
}
 

2Dcube

Member
Good to know. I'll use whatever's easier for me then.

Thanks for the tip. Interesting idea, it is also very useful when you want to remove items within the loop.
 

TheouAegis

Member
Also, global gets "pulled to the top" as well. I think it gets polled at the start of the game, actually. It doesn't set the variable right away, but it preallocates the memory.
 

2Dcube

Member
A further note: If your code's logic permits it, a better idea to reduce variable usage is to iterate backwards so that the terminating condition can compare to a fixed literal instead of an expression that needs to be evaluated.
Code:
for (var i = ds_list_size(items)-1; i >= 0; i--) {
  do_something_with(items[| i]);
}
Apparently some modern compilers check if a list is changed within the loop, and if not they cache list.size(). In general it could also be more efficient as compilers may be written to expect standard loops.
I have no idea if GMS is that advanced though.
 

TheouAegis

Member
Apparently some modern compilers check if a list is changed within the loop, and if not they cache list.size(). In general it could also be more efficient as compilers may be written to expect standard loops.
I have no idea if GMS is that advanced though.
The repeat function analyzes the terminus one time. All of the other loop functions analyze the terminus on every iteration.
 
Top