logoalt Hacker News

throwaway17_17today at 3:52 AM1 replyview on HN

Is there a reason Rust would not (as it was done in the ‘good ole days’) index the table via pointer arithmetic from .data? Also, I’m assuming that because you are discussing new devs, that they are not making the implementation decision to place the table on the heap and using Rist’s subscript operator, which I would understand Rust not doing as default. I can not think of a reason that the table should ever be put on the stack for reading a single value, so that being the default seems an oddly pessimistic default. I could be missing something regarding how Rust handles literal data ‘written out’ into source though.


Replies

tialaramextoday at 2:25 PM

The table is on the stack because we conjured into existence a temporary, so it's exactly as if the programmer had conjured the variable as a local by hand. Suppose our table is named SOUP

    const SOUP: [f32; 1000] = [ /* whatever */ ];
    let foo = something(blah_blah, blah) * SOUP[4];
    // The optimiser will see that SOUP[4] is exactly say 1.5_f32 so it'll just do
    // the same as if we'd calculated something(blah_blah, blah) * 1.5_f32
However

    let foo = something(blah_blah, blah) * SOUP[blah];
Now blah is a variable, we might need any value from SOUP, the optimiser doesn't know what values it might have - so a temporary is conjured into existence, equivalent to:

    let tmp = SOUP;
    let foo = something(blah_blah, blah) * tmp[blah];
You do presumably recognise that this now puts SOUP on the stack right? The temporary is equivalent, but without the explicitness.

Now if you know what you're doing you would of course have one single place in your program where you do this:

    static SOUP: [f32; 1000] = [ /* whatever */ ];
And now there's an immutable global named SOUP and like "the good ole days" we don't keep writing this huge data blob to the stack only to subsequently look at a single element. But that's not the thing the noob wrote so that's not what they get.

"Sufficiently smart compilers" are a very gradual miracle. In theory a compiler could realise this is a good idea, in practice today I doubt you will find such a compiler, so just write explicitly that you want a single variable if that's what you want.