Your static
variable will still be in static memory, neither in the stack nor the heap - but it’s true that it will be a direct variable in static memory rather than a pointer to another place in static memory. I don’t think the extra indirection will matter too much for performance, though - the compiler should be able to optimize it out.
This does not define a fixed length for the array, so does it create a pointer to the heap?
pub static PHRASES: &[&str] = &["alpha", "beta", "gamma"];
PHRASES
here is in static memory - a place loaded along with program code. In particular, it is a pointer to another place in static memory which stores the array.
And does this allocate a fixed array on the stack?
pub static PHRASES: [&str; 3] = ["alpha", "beta", "gamma"];
PHRASES
here is also in static memory, but unlike the example above, it’s just a 3-pointer long bit of memory.
As mentioned above, I don’t think one or the other will be better for performance. If you access it in a very tight loop the extra indirection might hurt, but even then I wouldn’t consider it important unless profiling found that to be the case.
And besides the above, if fast access matters more than other things, there’s also const
:
pub const PHRASES_CONST: [&str; 3] = ["alpha", "beta", "gamma"];
This will insert PHRASES_CONST
onto the stack whenever it’s used - it’s not stored separately from the code static memory (well, the strings in it are, but not the array itself). It acts as though ["alpha", "beta", "gamma"]
were written instead of PHRASES_CONST
whereever it’s used. I wouldn’t recommend this method because it means your array will be duplicated every time a different function uses it, and it will be created on the stack every time the function is called, but it’s another alternative if profiling does show you this is a problem.
I’ve also brought it up because I think you might have been thinking static
acts like const
does?
Hope the distinction between those and further explanation helps.