2 Structuring data for performance
This chapter covers
- Struct vs class - How data affects performance.
- Stack vs heap - How memory affects performance.
- Copying by value vs by reference - How data passed to functions affects performance.di
- Intricacies of struct allocations in C#.
- Data locality and arrays of structs vs arrays of classes.
- Data types - How data types affect performance.
In Chapter 1 we learned how data locality can improve performance by leveraging modern CPU architecture. We saw that using arrays is an easy, simple way to practice data locality and minimize cache misses. In this chapter, we’ll look at how to structure our array data in memory to maximize performance. We’ll cover what kind of objects we should use to store our arrays, what types of arrays we should create to solve different kinds of problems, and how different primitive data types can affect our performance.
Note
While the examples in this chapter are all in C#, and some of the content is specific to C#, the topic of choosing what object and data type to store our data is relevant for other languages as well.
We’ll start by examining how struct and class differ in how they are stored in memory in C# and when we should use each one.
2.1 Struct vs. class - how data affects performance
In Chapter 1 we solved our data locality issue by placing all our enemy data in arrays under a class called EnemyData, as seen in Listing 2.1: