Godot Version
v4.3.stable.official
Question
extends Node2D
func _ready() -> void:
var s := Time.get_ticks_msec()
var arr: PackedInt32Array
for i in range(100_000):
arr.append(f(i))
var e := Time.get_ticks_msec()
print(e-s)
func f(i: int) -> int:
var res := i * i
return res
takes ~60-65ms
replace arr.append(f(i))
with arr.append(i * i)
takes ~5-6ms
that is an extreme difference. how come there is such an overhead in calling a function? i dont see this is the other languages i use. it makes me want to minimise the number of functions i write since i dont know if i may be calling them in a loop at some point. which is a shame. is there anyway to optimise function calls?
gdscript is otherwise a very fine and fast enough language, but this is one pain point that’s bothering me
3 Likes
Is this also the case with the following?
func f(i: int) -> int:
retrun i * i
1 Like
that only makes ~3ms difference, so yea roughly the same
anyone know anything? is this overhead also a thing when using c#?
Running it on my macBook Air it takes 21ms using the function, and 4ms using the direct multiplication. And given it’s called in a loop 100K times, each function call is taking (17ms / 100K) or 170ns.
That’s higher than I’d expect for a compiled language like C(++), and higher than I’d expect for .NET. Having just run a quick test on a static C# function it takes ~3ns to call a function on my mac, although I suspect virtual C# functions might be closer to 15ns.
However, given GDScript is interpreted, I’d expect it to take longer to call a function, and 170ns doesn’t sound that bad. For most use cases I’d say it’s immaterial, but if you do ever want to run some fast code in Godot you could either optimize by pulling the code inline from a function, or you could use .NET for the performance sensitive bits.
2 Likes
hi thanks for the reply. given that im writing a fairly performance critical application for a school project (so not a game) and there are a load of loops going on
i use a 7 year old cpu haha and the ones in the school computers are even older…
i may have to consider rewriting things in c#. i would’ve liked to just write everything in gdscript. im just wondering why this is and if it can be optimised at all or if that’s just the technical nature of gdscript.
Sadly function calls are expensive, even in compiled languages; though it’s more like 2x slower rather than GDScript’s 10x slower. Compiled languages often have the benefit of aggresive and automatic inline-ing of functions too.
GDExtensions will help even more for such performance concerns. Does really well with loops and math; if most of your CPU time is away from engine calls like physics or scene tree manipulation I’d recommend it.
1 Like
ive been looking at gdextension but it seems really difficult to get into 