←back to thread

Four Years of Jai (2024)

(smarimccarthy.is)
166 points xixixao | 1 comments | | HN request time: 0.203s | source
Show context
spacechild1 ◴[] No.43730030[source]
> because most Javascript programmers are entirely unaware of the memory allocation cost associated with each call to anonymous functions

How does calling an anonymous function in JS cause memory allocations?

replies(2): >>43730166 #>>43731652 #
nmilo ◴[] No.43731652[source]
Probably misspoke, returning or passing anonymous functions cause allocations for the closures, then calling them causes probably 4 or 5 levels of pointer chasing to get the data that got (invisibly) closed over
replies(1): >>43731998 #
spacechild1 ◴[] No.43731998[source]
I don't think there is much pointer chasing at runtime. With lexically scoped closures it's only the compiler who walks the stack frames to find the referenced variable; the compiled function can point directly to the object in the stack frame. In my understanding, closed over variables have (almost) no runtime cost over "normal" local variables. Please correct me if I'm wrong.
replies(1): >>43738613 #
nmilo ◴[] No.43738613[source]
I meant more like storing closures to be used later after any locals are out of the stack frame, but tbh that's an abstraction that also causes allocations in C++ and Rust. On the other hand, no idea how JS internals work but I know in python getting the length of an array takes five layers of pointer indirection so it very well could be pointer to closure object -> pointer to list of closed variables -> pointer to boxed variable -> pointer to number or some ridiculous thing like that.
replies(2): >>43739620 #>>43740064 #
1. spacechild1 ◴[] No.43740064[source]
In C++, lambda functions don't require dynamic memory allocations, only type erasure via std::function does (if the capture list is too large for small-functiom-optimization)

However, C++ lambdas don't keep the parent evironment alive, so if you capture a local variable by reference and call the lambda outside the original function environment, you have a dangling reference and get a crash.