Skip to content

Discuss: lazy_static use too much stack space #230

Open
@fan2nd

Description

@fan2nd

There is a little test program.

use lazy_static::lazy_static;
use std::{
    arch::asm,
    sync::atomic::{AtomicUsize, Ordering},
};

static SP_RECORD: AtomicUsize = AtomicUsize::new(0);

fn get_sp() -> usize {
    let sp: usize;
    unsafe {
        #[cfg(target_arch = "x86_64")]
        asm!("lea {}, [rsp]", out(reg) sp);

        #[cfg(target_arch = "aarch64")]
        asm!("mov {}, sp", out(reg) sp);

        #[cfg(target_arch = "riscv64")]
        asm!("mv {}, sp", out(reg) sp);
    }
    sp
}

const LEN: usize = 1024;

lazy_static! {
    static ref TEST_DATA: [usize; LEN] = {
        SP_RECORD.store(get_sp(), Ordering::Relaxed);
        let mut arr = [0; LEN];
        for i in 0..LEN {
            arr[i] = 2 * i;
        }
        arr
    };
}

fn main() {
    let old_sp = get_sp();
    println!("Old SP: 0x{old_sp:x}");
    let first = TEST_DATA[0];
    let new_sp = SP_RECORD.load(Ordering::Relaxed);
    println!("New SP: 0x{new_sp:x}");
    println!("{first}");
    println!("SP difference: {}", old_sp - new_sp);
}

Then this is the result in release mode.

     Removed 58 files, 1.5MiB total
   Compiling spin v0.9.8
   Compiling lazy_static v1.5.0
   Compiling lazy v0.1.0 (/Users/fan/lazy)
    Finished `release` profile [optimized] target(s) in 0.14s
     Running `target/release/lazy`
Old SP: 0x16b1b2990
New SP: 0x16b1b0970
0
SP difference: 8224

I can not understand. The TEST_DATA should in bss section, why this init funtion used the similar space (8224 <> 8*1024) and did not to edit TEST_DATA directly?

lazy_static! {
    static ref TEST_DATA: [usize; LEN] = {
        ……
    };
}
fn __static_ref_initialize() -> [usize; LEN] {
    ……
}

Is this way below better? Try to pass a mutable reference into __static_ref_initialize.

fn __static_ref_initialize(TEST_DATA: &mut [usize; LEN]) {
    ……
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions