4 ms·
Probably misspoke, returning or passing anonymous functions cause allocations for the closures, then calling them causes probably 4 or 5 levels of pointer chasi
by nmilo 1y ago
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
- spacechild1 1y agoI 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.
- nmilo 1y agoI 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.
- steveklabnik 1y agoJavaScript is almost always JIT’ed and Python is usually not, so I wouldn’t rely on your Python intuition when talking about JavaScript performance. Especially when you’re using it to suggest that JavaScript programmers don’t understand the performance characteristics of their code.
- nmilo 1y agoWhere exactly did I suggest that?
- steveklabnik 1y agoI think I confused you with the author of the post, something about the way you phrased your original post in this thread. Re-reading it now I'm not sure why I thought that! Sorry!
- spacechild1 1y agoIn 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.