Does using self incur an overhead?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By HarpyEagle
:warning: Old Version Published before Godot 3 was released.

In GDScript using the self keyword to access a member variable is optional. However I often prefer to include it for readability - it makes variables which belong to the object’s scope stand out. However, I am wondering if using self has a performance penalty. While I am sure it must be small, I’d like to know in case I am writing code that has to execute many times each frame (e.g. very frequently used functions).

:bust_in_silhouette: Reply From: Zylann

From my benchmark, I can tell even in exported games it makes a difference, probably because GDScript lacks of a few straightforward optimizations at the moment.

However, the impact is very small. I have a test doing a += member, where member is either expressed as is, or with self. Executed 1000000 times, the result is that the version without self takes 45 seconds, while the version with self takes 47 seconds (I took care of removing the cost of iteration itself).

using self executes the setter and getter too, right?

eons | 2017-05-04 03:29

Yeah in some specific cases using self will have a difference because it is seen as “using the object from outside”, meaning setget functions will be called: GDScript reference — Godot Engine (latest) documentation in English

Zylann | 2017-05-04 12:46

Indeed, I was asking about the case where there is no setter or getter.

HarpyEagle | 2017-05-04 23:53

aahh… that’s a mean little detail - Thanks for the link, I’ve overlooked it in the manuals. I experienced some strange behaviour using self and setter/getter the last days. This explains it!

phatsen | 2018-04-29 18:01