Differences in memory allocation

To understand how using certain data types can affect your application's performance, you need to understand how and where they are placed into your application's memory and how they are accessed. Every application uses a certain amount of the host device's RAM (Random Access Memory). The memory that an application uses can be divided into two segments: the stack and the heap.

The heap is a section of reserved memory for your application that can grow and shrink as needed. The objects that are stored on the heap are stored in no particular order and the objects themselves can grow and shrink the memory they use on the heap as needed too. This means that, sometimes, a lot of memory will have to be reshuffled to accommodate the insertion of a new object in the heap. The following image visualizes this:

As you can see, the different objects in memory get moved around inside of the heap to make sure the new object fits. This dynamic nature of the heap makes inserting objects on the heap quite slow because you never know whether the object you are about to insert will fit immediately or whether something has to be reshuffled. The ability to reshuffle memory to fit new objects or to accommodate an existing one does make it a very good fit for objects that have a variable or growing size. The type of objects that are allocated on the heap are always reference types. This means that all class instances you create will be allocated on the heap. The same is true for closures since they too are reference types. Value types, on the other hand, are always allocated on the stack.

The stack is a section of RAM with a fixed size that is available to your application. Objects in the stack are always added and removed in a fixed manner, the last object to be added to the stack will be the first object that is removed from the stack. Because the stack behaves in such a predictable way, it is a very fast and efficient way to store and retrieve objects. The stack is always in the correct order and objects are never shuffled around to facilitate new objects. The fact that value types are allocated on the stack makes them very lightweight and performant when compared to reference types.

You might think that the performance of value types makes choosing between values types and references types a no-brainer. Unfortunately, choosing the correct type isn't that easy. The next section of this chapter will explain why, and provide you with enough information to make informed decisions about the types you use in your own apps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset