So for i in range(0,10):
creates an Array containing the numbers 0 through 9 and then iterates over the Array, providing the values through i. This is convenient, but it takes significantly more processing and often is overkill. Even if you’re literally looping over an Array, doing for element in someArray:
is going to run much much slower…
No, it doesn’t work that way. Let’s read the docs: GDScript reference — Godot Engine (stable) documentation in English
for i in range(3):
statement # Similar to [0, 1, 2] but does not allocate an array.
Yes, you can use range
to create an array of integers, but when it is used in a for
loop, array is not allocated.
Let’s test which one is faster, for
or while
.
const LOOPS := 10000000
func test1():
var t0 = Time.get_ticks_msec()
for i in range(LOOPS):
for j in range(10):
pass
var t1 = Time.get_ticks_msec()
prints("time for :",t1-t0,"ms")
func test2():
var t0 = Time.get_ticks_msec()
var i := 0
var j := 0
while i < LOOPS:
i += 1
j = 0
while j < 10:
j += 1
var t1 = Time.get_ticks_msec()
prints("time while:",t1-t0,"ms")
On my computer, using Godot 4.2 and release build, results are:
time for : 979 ms
time while: 3388 ms
for
takes only about 30% of the time that while
takes.
Then how about iterating arrays of nodes?
var nodes: Array[Sprite2D] = []
const NODE_LOOPS := 1000000
func test3():
var t0 = Time.get_ticks_msec()
for i in range(NODE_LOOPS):
for n in nodes:
if n.frame == 1:
pass
var t1 = Time.get_ticks_msec()
prints("time nodes for :",t1-t0,"ms")
func test4():
var t0 = Time.get_ticks_msec()
for i in range(NODE_LOOPS):
var j := 0
var len := nodes.size()
while j < len:
if nodes[j].frame == 1:
pass
j += 1
var t1 = Time.get_ticks_msec()
prints("time nodes while:",t1-t0,"ms")
func _ready():
for i in 20:
nodes.push_back(Sprite2D.new())
test3()
test4()
Results are:
time nodes for : 2145 ms
time nodes while: 2757 ms
In this test accessing sprite’s frame
property takes a lot of time, but it is clear that for
is faster, taking about 80% of the time that while
takes.
So using for
is faster and much less error prone than while
. Of course, sometimes there are reasons for using while
, but performance is not one them.