Memory Usage
How do implicit conversions affect memory usage in my program?
Understanding how conversions affect memory usage is important, especially in games where performance matters. Let's break this down:
Converting to Bigger Types
When you convert a smaller type to a bigger type, you use more memory:
#include <iostream>
using namespace std;
int main() {
// Small number types
char SmallNumber{65}; // Uses 1 byte
int BiggerNumber{SmallNumber}; // Uses 4 bytes
// The computer needs extra memory to
// store the same value!
cout << "Original char: " << SmallNumber;
cout << "\nAs integer: " << BiggerNumber;
}
Original char: A
As integer: 65
Converting to Smaller Types
Going the other way can save memory but might lose information:
#include <iostream>
using namespace std;
int main() {
// Big number type - uses 8 bytes
double BigDecimal{3.14159265359};
// Uses 4 bytes
float SmallDecimal{
static_cast<float>(BigDecimal)};
cout.precision(10);
cout << "Original: " << BigDecimal << "\n";
cout << "Converted: " << SmallDecimal;
}
Original: 3.141592654
Converted: 3.141592741
Memory Usage Guidelines
Here's what to remember about conversions and memory.
Converting to bigger types:
- Always safe - no data loss
- Uses more memory
- Might be slightly slower
Converting to smaller types:
- Might lose data
- Uses less memory
- Usually not worth the risk just to save memory
Most of the time, you should:
- Choose the right type for your data from the start
- Don't convert just to save memory unless you're sure you need to
- Use uniform initialization to catch accidental conversions that might lose data
Implicit Conversions and Narrowing Casts
Going into more depth on what is happening when a variable is used as a different type