• Hey! Guest! The 40th (!!!) GMC Jam will take place between February 25th, 12:00 UTC to March 1st 12:00 UTC. Why not join in this very special anniversary jam! Click here to find out more!

GMS 2.3+ Constructor vs list of structs, what is better?


My inventory is a ds_list of structs and it works fine, but I was wondering if there's a reason to use a constructor instead.

My current code:

inventory = ds_list_create();

for (i = 0; i<inventorysize; i++){
    inventory[|i] = {
        itemtype : empty,
        charges : empty,
        quality : empty,
        rust : empty,
        identified : true


Firehammer Games
I personally use struct constructors for about everything. It feels more natural to me along with the 'new' keyword since its closer syntax to what I'm used to from other languages' constructors. However, if you are comfortable with what you are doing, I see no reason to switch to a constructor for it. I have a hunch that this way is faster than constructors as well(since those create the slight function call overhead).

The one thing you get with a constructor though is a guarantee of variables and methods. In your case, it doesn't matter since you are just making a quick inventory thing from the looks of it. But if you were making something that needed methods to be defined, and if you were creating those structs in any number of places instead of in this single use case like your inventory, a constructor would be better, because you can guarantee to define static methods, and be sure that all the variables you want in it are there(instead of having a chance to forget one later).


I'd recommend using constructors. Semantically, constructors create structs of a single type, while struct literals (like you're using) create structs of an anonymous type. If you're making a list of multiple structs of the same type, future compiler optimizations can work with the semantic difference, leading to a performance or memory use improvement when you're using constructors as opposed to struct literals.

By making a constructor, it's also easier to control the struct. For example, if you create a new InventoryItem(itemtype, charges, quality, rust, identified), you can write a piece of code inside the constructor that creates hidden data automatically if identified is false. You can also define a static method item.damage(), increasing rust or decreasing quality or something. Since it's a static method, it will only be defined in one place. It's the difference between having a hundred identical functions with a single variable pointing to each, or having one function, and a hundred variables pointing to it (the latter saves so much space).

In fact, there are very few places (outside configuration files) that I would consider using a struct literal over a constructor.