question on efficiency of my code?

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

In my game I have some objects in the game that the player can interact with. When interacting with these the player can request certain things at a certain time delay. Think of it as them orderings something. They are able to order multiple things from any one object and each thing may take a certain time to return.

When the item is ordered I add it to a dictionary in my singleton script as below:

var dict = {"OBJ1": { "Item": 10, "item2": 60}, "OBJ2": {"Item3": 55, "Item7": 90}, etc.} 

Now i have a function that fires every second and filters through all of these reducing the number by a second and when 0 is reached the player is told that that item is ready to collect from that object.

This works fine but I am querying whether it is the most efficient way of doing this or may there be a better way of performing this action. I also was wondering if this function should be a new thread? Could somebody perhaps give me some guidance on when functions should be threaded and when not?

Thanks!

You’re already only checking it once per second as opposed to every frame, so, unless it’s a huge array, I doubt it will matter much. Here are a couple of thoughts If you expect the array to grow to a size where it would impede performance:

Rather than having a countdown time in the array for each item and decrementing all of them every second, use an expiration time in the array instead, and keep a running timer variable in the module. That will allow you to do a compare rather than changing its countdown value which should be faster. Also, depending on the average number of items ordered at once and delivery duration time, etc., it might be beneficial to sort the array (by time) after an order(s) is placed. Then, each time that you start to iterate through the array, if/when you get to an item that is not ready to be delivered, you know that there are no more deliverables in the array this check, and exit the loop early.

Michael Paul | 2017-11-06 03:53