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:

2.2 Stack vs heap - how memory affects performance

2.2.1 The stack

2.2.2 The heap

2.3 Passing by value vs. by reference - performance and common issues

2.3.1 Copying by value and common issues

2.3.2 Copying by value and performance

2.4 The intricacies of struct allocations in C#

2.4.1 Structs as member variables

2.4.2 Structs with arrays

2.4.3 Structs with Strings

2.5 Data locality and contiguous memory - arrays of structs vs arrays of classes

2.6 Data types and Performance

2.6.1 Performance

2.6.2 Memory

2.7 Conclusion

2.8 Summary