Brendan Eich tells how to prevent JavaScript memory leaks

The JavaScript founder details where developers can go wrong and the straightforward methods to stay on track

By , InfoWorld |  Software, JavaScript

Leaks can also result from careless JavaScript code that creates new objects and stores them in a big table of all objects ever created or from similar mistakes. These types of leaks happen in Java and other languages due to developer error, not internal implementation bugs. Developers generally know to avoid them, but they can be hard to detect sometimes. That's where leak-finding tools can help.

InfoWorld: What problems result from these leaks?

Eich: In brief, a garbage collection must be able to find all "live" objects, then collect remaining unreachable objects, which are "garbage" and by definition "dead." If a garbage-collection implementation misses some dead objects due to a logic bug, the memory consumed by those unreachable objects will not be reclaimed [which can lead to slow or unresponsive programs]. The JavaScript-level leaks, where a developer unwisely saves every object created in a big and automatically grown table, for example, are easier to understand.

InfoWorld: How can developers prevent JavaScript memory leaks?

Eich: Developers shouldn't put all objects in a big table or other similar structure such as a linked list.

They should report to browser vendors any inevitable runaway memory growth if the developer can run that same JavaScript code successfully in other browsers without such growth. This probably means the ever-growing browser has a leak in its implementation code. But there could be a browser-specific JavaScript code path, so developers have to be positive that exactly the same code is in use on the control browser that does not grow.

InfoWorld: Once leaks occur, what can be done to fix them?

Eich: Leaks require prevention in general, not reactive repair on a running system. If a developer's JavaScript code somehow misses a leak, it is not possible to automatically fix it [on the user's system after the fact]. If a developer did have a big table that carelessly stored references to all objects ever created, of course, you might treat it as a cache and purge old object references from it, but that's not really a leak, just a cache that needs careful tuning and reclamation policy implemented by your JavaScript.

Memory tools can also help. A memory profiler can show which objects are taking up the most memory. Then, a garbage-collection tracing tool can tell which program values are causing those objects to be kept.


Originally published on InfoWorld |  Click here to read the original story.
Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question