6 – 04 L C And RAM V1 RENDER V1

Let’s go into some detail about how C++ uses RAM. You can think of RAM as a set of slots where you can store information. When your program executes data, it is usually stored in RAM. This data can be overridden and in fact when you turn your computer off, data in RAM is erased because RAM is volatile, hence RAM is used for temporary storage. Take a simple example like declaring a character variable, when the x variable gets declared, your program will go into the computer’s RAM and reserve space. How much space will depend on the variable’s type. In the case of a character variable one byte gets reserved. Then when the x variable gets defined, the binary value for the character gets stored in RAM. In C++, the smallest unit of memory that your program can keep track of, is one byte. So what happens if your program defines another character variable. The compiler will then assign this character to the next available byte. And what about an integer variable, well a 32 bit integer would take up four bytes of memory. So an integer variable would take up four spaces in RAM, the compiler and computer architecture will determine exactly how much space each variable needs in order to optimize the program. In general, the next variable gets placed above the previous variable. Each byte also has an address so that the program knows where to find the variable. This entire area where C++ places variable values has a special name called the stack. C++ uses the stack to efficiently manage reading and writing to memory for you. When a function terminates and variables fall out of scope, the compiler freeze up or deallocates these memory locations working backwards. Besides the stack, the compiler offers other parts of memory for different tasks like storing the text of your code and reserving space for global variables. C++ also provides an area of memory called the heap, where you can manually control when a variable gets removed from memory. But how is all of this related to code optimization? Reading from and writing to memory take time and thus can make your program slower. If you declare and define a variable that you don’t actually need, your program can slow down. If you copy a variable unnecessarily, your program can also slow down. The stack also tends to be more efficient than the heap, so how you declare your variables can end up affecting your program’s performance. Hence, the more you understand the consequences of each line of code, the better you can optimize. That’s what we mean when we talk about empathizing with the computer. Understanding the limitations of your hardware, help to make better coding decisions.

%d 블로거가 이것을 좋아합니다: