Size of Variables Matter
Why Sizeof Variable Matters?
- Fixed-size types exist in C++, Rust (Systems Programming Languages), as compared to Python and JavaScript (Scripting Languages).
- In SPLs, you have explicit control over how much memory is used to represent data.
- Fixed types tell the compiler how much space is needed in memory.
- Computers operate in bytes (8 bits); hence sizes always appear in multiples of 8 (not arbitrary values like 3, 4, or 5).
- We might allocate more space to something that requires a smaller range by definition.
- Hence, we end up using more memory than necessary in scripting languages (since resource allocation is handled by the interpreter).
- Enforcing a fixed type avoids mis-allocations (e.g., rejecting a negative value for an
agevariable).
Performance Implications
- In scripting languages, once the interpreter assigns memory to variables, how does it later know whether those bits represent a string, number, or something else (since everything is machine code)?
- This is solved by attaching runtime type metadata (tags) to values.
This enables runtime type checks and errors (Python throws errors; JavaScript often doesn't).
- These tags require extra memory.
- Tags must be:
- initialized,
- read,
- compared,
- written at runtime.
All of this adds runtime cost. As a result, the CPU spends time performing comparisons instead of arithmetic.
- In compiled languages, this overhead is removed.
The compiler directly generates assembly that performs arithmetic without runtime type checks.
What if size is unknown at compile time?
- We keep references to memory regions that can grow or shrink at runtime (stack or heap).
- Stack: fixed-size, fast, scoped
Heap: dynamic-size, flexible, slower