0 votes

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).

in Engine by (35 points)

1 Answer

+5 votes
Best answer

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).

by (28,833 points)
selected by

using self executes the setter and getter too, right?

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: http://docs.godotengine.org/en/latest/learning/scripting/gdscript/gdscript_basics.html#setters-getters

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

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!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.