How to store data faster?

Godot Version

4.2.1

Question

How can data storage be faster if the number of variables does not change? For example, I have a number of parameters that I need constant access to in order to read and overwrite:

var x = 0
var y = 1
var z = 2

or

var n:Dictionary = {“x”:0, “y”:1, “z”:2, …}

or

enum {x, y, z, …}
var n:Array = [0, 1, 2, …]

optimization is important to me, convenience is not important.

I would imagine the fastest of those would be an implementation detail under the hood and may actually vary over time.

You could do timing tests yourself, say run each of those thousands of times and time the difference.

First of all, im new in Godot myself, but i can tell as programmer.
Im not sure how GDScript compile or is managed directly, but:

Dictionary seems to be like hashmap in Java.

It should have access O(1) in worst cases O(n) it depend if “hash” will dupplicate.

var x = 0
var y = 1
var z = 2

This is fastest O(1) always but code will be very unfriendly if a lot of it.

enum {x, y, z, …}
var n:Array = [0, 1, 2, …]

This should also be O(1) in both cases, array access in theory should be almost same like variable access (until its not equal to C array or enum)

So as you see every case should be fast enough, but if you mean any micro-optimization-speed i would sort fast-to-slow like: var<Array<enum<Dictionary

If its about “if the number of variables does not change”
Then const/enum/array/var is all fine. var in fact should be constants if value do not change.

But…

The main problem is… why do you ask?
Because since all access here should be fast enough it seems like your code contain different issue that might cause it work very slow.

1 Like

thank you, I don’t have any problems with the code yet, it’s just that until the code becomes huge, I want to follow the right optimized way.
I will use var.

all var,Array,enum will be fine. Just make your code readable, that is often more important. Most “slow code” comes from programmer mistakes like over-calling some methods.

the big gap will be between them and Dictionary. While Dictionary should be very fast in case where you dont want “loop array to find element”. Dictionary will be faster in case like this.