1

I have two methods below:

function foobar() {
   const viewState = getViewState();
   return () => { use(viewState); }
}

function foobar() {
   return (viewState) => { use(viewState); }
}

Can you please let me know if there is memory leak from any of these functions?

I was told by someone that the 1st method is leaking since the viewState is passed from outside and it is being held inside the closure without being released, whereas the 2nd function is not leaking because viewState is passed as a parameter.

If that's true, I am interested in more detailed explanation.

  • Why the 1st method is leaking memory? Is it because the program is unable to remove viewState from memory automatically after it executes the code inside the arrow function?
  • Why the 2nd method where passing viewState as parameter is not causing memory leak?
flyingbee
  • 601
  • 1
  • 7
  • 17
  • 4
    It's only a leak if it holds on to the memory longer than it's needed. The first one will preserve the `viewState` as long as you have a reference to the function that it returns. That's not a leak because you can call that function repeatedly to use it. – Barmar Apr 04 '22 at 21:08
  • 1
    long discussion here: [Memory leak risk in JavaScript closures](https://stackoverflow.com/questions/11186750/memory-leak-risk-in-javascript-closures#:~:text=According%20to%20Microsoft%2C%20closures%20are%20the%20cause%20of%20memory%20leaks.) – pilchard Apr 04 '22 at 21:08
  • "*I was told by someone that the 1st method is leaking*" - that's rubbish. Yes, they're right that there's a closure over `viewState` (which doesn't have anything to do with arrow syntax specifically, it's the same for all functions), but if this is the required functionality then go with it. Whether the memory is actually leaked depends on how the closure is used/retained and whether it actually needs the `viewState`. We cannot tell without more context. – Bergi Apr 04 '22 at 21:10

0 Answers0