What's the difference between = and := performance-wise? and why should = be used?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ChillFire

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?

:bust_in_silhouette: Reply From: AlexTheRegent

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.