Code optimization: Struct and Class

Andrea Alicino
1 min readOct 22, 2021

Speaking of optimization it seems appropriate to dwell on the difference between struct and class.

Let’s start with a small definition of both

A class is a user-defined model or prototype from which objects are created. A class combines fields and methods into a single unit.

A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both contain a bunch of different data types.

More specifically, structs are defined as value-types while classes are reference-types and this affects memory management.

Value-types are allocated in the stack, the cost of allocation is cheaper than a reference type that is allocated in the heap.

Classes compared to struct can inherit from other classes, but to create a new instance we have to use the keyword “new” that we have seen that used in the wrong places can create a waste of resources.

Other differences concern the possibility to be abstract and virtual that concerns only classes.

Ultimately, even the choice of the type of variable we have to use affects the efficiency of the code and the game itself.

--

--

Andrea Alicino

Game Developer Unreal Engine/Unity. Computer science graduate. Seeking new opportunities.