Course contentsShow
← Rust
Lesson 1012 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

Static Data and Reference Counting

Decide whether to use global static constants versus runtime-allocated Arc instances.

In this lesson, you will learn how to choose between hard-coded static data and heap-allocated Arc instances when sharing data across your application.

Static Data: The "Fixed at Compile Time" Approach

When you use the static keyword, you are telling the compiler to allocate memory for that data at the exact moment your program starts. This memory exists for the entire duration of the program's life.

Because static data is "baked into" your binary, it requires no heap allocation at runtime. If you have a configuration map or a large lookup table that never changes, a static reference is incredibly efficient. It doesn't need reference counting because its lifetime is effectively infinite; you don't have to worry about cleaning it up.

Arc: The "Flexible at Runtime" Approach

In contrast, Arc (Atomic Reference Counted) pointers manage data that is allocated on the heap at runtime. You use Arc when:

  1. Dynamic Data: The data is computed or loaded (e.g., from a network request) after the program has already started.
  2. Shared Ownership: Multiple parts of your code need to own the data, and you don't know which one will finish last.
  3. Dynamic Lifetimes: You need to free the memory as soon as the last reference is dropped.

Choosing Between Them

Think of static data as a library book that stays on the shelf for the life of the library, and an Arc as a personal copy you check out.

use std::sync::Arc;

// Static data: Zero heap allocation, infinite lifetime.
static CONFIG_NAME: &str = "AppConfig";

fn main() {
    // Dynamic data: Heap-allocated, managed by reference counting.
    let shared_state = Arc::new(vec![1, 2, 3]);

    let thread_handle = shared_state.clone();
    // ... move thread_handle to a thread ...
}

If your data is constant and known beforehand, always prefer static. It avoids the runtime overhead of incrementing and decrementing reference counters. Only reach for Arc when you require the flexibility of heap allocation or when the data's lifecycle must be determined by the program's execution flow.

Key Takeaway: Use static for global, unchanging constants to avoid runtime costs, and reserve Arc for heap-allocated data that requires dynamic lifecycle management.