Hacker News new | ask | show | jobs
by xigoi 1459 days ago
> It's a memory, not speed, optimization

I assumed it was a speed optimization too, since a goto is faster than creating a whole stack frame and then destroying it again. Is that not the case?

By “inside a loop”, I meant a loop that is independent of the function, like this:

    function foo() {
      if (…) {
        foo();
      }
    }

    for (let i = 0; i < 1000000000; ++i) {
      foo();
    }
Here it won't cause a stack overflow either way (if foo is used on small data), but I'd assume that the loop would amplify the effect of even a small performance optimization.
1 comments

> since a goto is faster than creating a whole stack frame

Yes, as I mentioned in parentheses--creating a stack frame costs because it is writing to memory, other than that it's just an increment of the stack pointer register in compiled/JITted code. But it's not a large cost, so you usually won't notice it or at least not much. Especially if your recursion depth is small, as then the memory writes might not leave the CPU cache. Sure, making some code 10% faster by way of TCO can still be useful, and it's probably why C compilers are doing it (they don't guarantee general TCO so you're limited in what you can do with it, so the only guaranteed advantage is a little speed gain), but if we're talking some JavaScript app there will be worse problems. Especially, the problem that with large enough data you're going to allocate lots of temporary memory for the stack--that's something a user will notice. Especially if the memory temporarily used is not given back to the OS, which is the case in C, and I rather expect JavaScript as well, which will mean that every tab running JavaScript will have some amount of RAM tied down to (even if rare) temporary stack use.

> and then destroying it again

This is then really just a decrement of the stack pointer.

That makes sense, thanks. Now I'm curious, if popping a stack frame is just decrementing a pointer and the contents stay there, isn't it a security vulnerability?
Only if there's a way to access it. From within JavaScript you don't have access to it, unless there's a security hole in the VM. But yes, programs handling encryption keys generally overwrite the memory holding them before freeing it / letting it go, at least those written in C/C++. Either for the case of a security hole allowing access to such memory, or so that it doesn't stay around in process memory where another process on the same system with the necessary permissions (on Linux either root or the same user) can access its memory via debugging APIs. But it's not done for normal data.