Constants and Static Variable
Constants (const)
• Purpose: Compile-time fixed values that never change.
• Memory Efficiency:
• Constants are inlined at compile time, meaning the value is directly embedded wherever it’s used.
• No separate memory allocation at runtime, making them highly efficient.
• Use Case: Best for fixed, unchanging values like mathematical constants, configuration settings, or limits.
Example:
const PI: f64 = 3.14159; // Inlined wherever used
Static Variables (static)
• Purpose: Global variables that persist for the entire program’s lifetime.
• Memory Efficiency:
• Allocated at a fixed memory address in the program’s global memory.
• Access requires reading from that memory location, which is slightly less efficient than inlined constants.
• Mutable static variables may require synchronization in multi-threaded contexts, adding overhead.
• Use Case: Suitable for globally shared data or persistent, large structures.
Example:
const PI: f64 = 3.14159; // Inlined wherever used
Key Differences
Feature | Constants (const) | Static Variables (static) |
Memory | Inlined, no runtime memory allocation | Fixed memory address at runtime |
Performance | Faster (no runtime access cost) | Slightly slower (global memory access) |
Mutability | Always immutable | Can be mutable (with unsafe) |
Use Case | Lightweight, frequently used values | Persistent, globally shared data |
Which to Choose?
• Use const:
• For immutable, lightweight, and frequently used values.
• When maximum memory efficiency and performance are required.
Use static:
• For persistent, globally shared data or large structures.
• When you need a single memory location for data across your program.