0 votes

Hello and good day to you,
so I was wondering why should I ever use the = sign instead of the := sign when creating a variable, and my though process for that was :

  • First I know that := sets the type of the variable when assigning the value, meanwhile = only assign the value to the variable
  • I am currently learning C in university(computer science degree) and I learnt C# in my off-time, so logically speaking I know that an int32 takes less memory than an int64, and a float takes less memory than a double
  • so I though that if I do not assign a type to my var in GDscript, does that mean the engine will allocate enough memory for any and all data types?

and so I came to the conclusion that I should always use := instead of = since I am telling the engine that I'll be using a single type for the variable, thus reserving just the required amount of memory for it, and in turn affecting the performance for the better. But I know that I am a beginner in GDscript so I came here to ask you fellow friends/seniors to help me and tell me why should I use the = sign


TL;DR: := looks better than = performance-wise since it assigns a single type to the variable and reduce error-chance, so why should = be ever used when declaring a variable and what are some of it's pros?

Godot version 3.3.4
in Engine by (12 points)

1 Answer

0 votes

As of 3.x versions of Godot, there is no difference in := and = in terms of performance. The only reason to use it is to prevent some type-based errors, since it helps editor to understand types. Starting from Godot 4.0+ version, := will also have performance boost.

There are some situations where you can use = instead of := to make code a little bit cleaner. For example, Dictionary can't be null, so you have to return empty dictionary:

func do_something() -> Dictionary:
  return {}

And to check that function did something, you need to check your return using Dictionary.empty() method. This code can be simplified if you define return type as Variant (variable without type):

func do_something():
  return null

and then you can just check as if result != null

does that mean the engine will allocate enough memory for any and all data types?

Yes, it will allocate required memory dynamically when needed.

by (1,462 points)
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.