Best practice: Local variables in loops?
Monkey Forums/Monkey Programming/Best practice: Local variables in loops?
| ||
Hi, I just have a question regarding the declaration of local variables that are used in loops. It's best explained with an example. Version 1: Local value:Float For Local i:=0 Until 100 value = Rnd(0.0, 10.0) result += value Next Version 2: For Local i:=0 Until 100 Local value:Float = Rnd(0.0, 10.0) result += value Next It's not a very useful example, but I think it clarifies my question. Assuming that the variable 'value' will only be required in the loop, I'm just wondering if any of these code samples above is better in terms of performance. Is it better to declare the Local variable once before the loop starts, or to declare it in the loop which means that it is declared and destroyed on each iteration? Thanks Anatol |
| ||
Interesting question. To be honest I don't think it would make much difference. I'm pretty sure the runtime assigns stack space to the variable when you call the method/function, but it's only accessible within its own scope. |
| ||
Local variables should be on the stack so it's fine to have them in the loop. I always try to use local stuff as much as possible. Creating new objects is a different horse. These objects (like New Class...) are created on the heap which creates MUCH more overhead so it's a good idea to create them outside of the loop. Example for a variable: Local value:Int Local result:Int For Local i:Int = 0 To 100 value = Rnd( 1, 100 ) result += value Next Print result is the same (in terms of speed) as Local result:Int For Local i:Int = 0 To 100 Local value:Int = Rnd( 1, 100 ) result += value Next Print result BUT Class IntPair Field x:Int Field y:Int Method New( x:Int = 0, y:Int = 0 ) Self.x = x Self.y = y End Method End Class Local value:IntPair = New IntPair() Local result:Int For Local i:Int = 0 To 100 value.x = Rnd( 1, 100 ) value.y = Rnd( 1, 100 ) result += value.x + value.y Next Print result is faster than: Class IntPair Field x:Int Field y:Int Method New( x:Int = 0, y:Int = 0 ) Self.x = x Self.y = y End Method End Class Local result:Int For Local i:Int = 0 To 100 Local value:IntPair = New IntPair() value.x = Rnd( 1, 100 ) value.y = Rnd( 1, 100 ) result += value.x + value.y Next Print result |
| ||
Thanks for the reply and examples, Xaron. That makes sense. I'll check my project for new objects and see if I can avoid some overhead. I currently use a lot of vectors, so I'm almost certain I'll find some instances where I haven't used a best practice. Thanks! |