iLounge | All Things iPod, iPhone, iPad and Beyond

Sunday 10 October 2021

Differences of Struct and a class in iOS ?



Class usually stores data on heap memory where we need to manage memory allocations and deallocations manually because on heap memory does not destroy objects automatically after completing their respective tasks.Internally all these process takes some time to finish.

Classes are by default reference type so , whenever we create any instance for  any class functions for properties to hold. rather than creating a new copy they just creates a reference of the object . Where both the newly assigned object and existing object shares same memory address.

Thus how , altering the newly assigned object value can effect its existing object value because of same memory location.

Structs are stored on stack memory where objects gets stored on its individual stack and performs LIFO execution thus it makes easier to track and maintain the objects.

And moreover structs are fast compared to classes because stacks helps struct objects to destroy them immediately after performing its tasks. 

By default structs are value types . so , dealing with structs are pretty much easy because when ever we create any instance of struct object . It creates a copy of that instance . Hence modifications at one instance will not get altered at the other end because each instance has its different memory address.

Even many of apple libraries prefer structs over classes as it works faster and easier to maintain.