I have some very large objects that are used intensively, but occasionally in my Node.JS program. Loading these objects are expensive. In total they occupy more memory than I have in the system.
Is there any way to create a "weak reference" in JavaScript, so that the garbage collector will remove my objects when memory is low, and then I can check whether the object is and reload it again if it was garbage collected since my last access?
The particular use case I had in mind was cartographic reprojection and tiling of gigabytes of map imagery.
Is there any way to create a "weak reference" in Javascript, so that the garbage collector will remove my objects when memory is low?
No, Javascript does not have that.
I don't think a weakMap or weakSet will offer you anything useful here. They don't do what you're asking for. Instead, they allow you to have a reference to something that will NOT prohibit garbage collection. But, if there are no other references to the data, then it will be garbage collected immediately. So, they won't keep the data around for awhile like you want. If you have any other reference to those objects (to keep them around), then they will never get garbage collected. Javascript doesn't offer a weak reference that is only garbage collected when memory starts to get full. Something is either eligible for garbage collection or it isn't. If it's eligible, it will be freed in the next GC pass.
It sounds like what you probably want is a memory cache. You could decide how large you want the cache to be and then keep items in the cache based on some strategy. The most common strategy is LRU (least recently used) where you kick an item out of the cache when you reach the cache size limit and you need to load a new item in the cache. With LRU, you keep track of when an item was last used from the cache and you kick out the oldest one. If you are trying to manage the cache to a memory usage size, you will have to have some scheme for estimating the memory usage of your objects in the cache.
Note that many databases will essentially offer you this functionality as a built-in feature since they will usually contain some sort of caching themselves so if you request an item from the database that you have recently requested, it probably comes from a read cache. You don't really say what your objects are so it's hard for us to suggest exactly how they could be used from a database.
Related
In attempting to determine how to most effciently perform a series of repetitive steps, I find that I know very little about memory usage in a web browser. I've read about the garbage collector and memory leaks several times before but that is still very little. The specific scenario in which I am interested is as follows.
A set of data objects is retrieved from indexedDB using a getAll statement over a key range. The data is all text and would never exceed 0.25MB and is likely always less that 0.1MB.
The array of data objects is passed to a function that builds a node in a document fragment and replaces a node in the DOM.
As the user modifies/adds/deletes the data, the state is saved in the database using a get/put sequence, and an add if a new object is built. This is performed on one object at a time, not on the whole array.
When the user is finished, the next set of data is retrieved and the DOM node is replaced again. The users can navigate forward and backward through the packets of data they build.
After the new node is built, the variable that holds the array of data objects is no longer used, and is set to null in attempt at avoiding any potential memory leaks. But I started thnking about what really happens to that data and memory allocation each time the functions are invoked.
Suppose the user rapidly clicks through a series of data packets. Each time the data is retrieved and the new nodes built and replaced in the DOM, is the same memory space being used over and over again, or does each invocation take up more space, and the memory used in the former invocations is later released by the GC, such that rapidly clicking through ten nodes temporarily takes up ten nodes worth of data? I mean this to include all the data involved in these steps and not just the DOM node being replaced.
One reason I ask is that I was considering holding the array of data objects in RAM, and updating the objects as the user makes edits/builds more obejcts, and then just using a put operation to record it in the database rather than a get/put sequence. And that made me wonder what takes place if that array is held in a property of one of the functions. Will the data allocation of the function property repeatedly be re-used with each new invocation or will it take up more space each time also, until former invocations are released?
I thought maybe that, even when the variables are set to null after the new nodes are built, the GC may take time to release the memory anyway, such that memory is always being used and it may as well hold one data packet at a time and eliminate the need for a get and waiting for the onsuccess event to update the object and then put it back again.
Of course, all of this works very quickly with the get/put sequence, but I'd like to understand what is happening regarding memory; and, if setting the variables to null and not holding the array in RAM is really saving nothing, then there is no reason to use get, and the less work done may make it less likely that, after a user works with this tool for an hour or two, there would be a memory issue.
Thank you for considering my rather novice question.
Thank you for the comments. Although they are interesting, they don't really concern what I am asking. I'm not asking about memory leaks, but only commented that the variables are being set to null at the close of the functions. They are set to null because I read that if the references to an area of memory are 'broken' it helps the GC's mark-and-sweep algorithm identify that the particular area of memory may be released. And, if some type of reference back to a variable remains, it will at least be pointing to null rather than an area of remaining data. Whether or not that is true, I don't know for sure; but that is what I read. I read many articles on memory leaks but these three, article 1, article 2, and article 3 I was able to find again easily to provide for examples. In article 3, page 5 shows setting a variable to null as a way to protect against memory leaks by making an object unreachable.
I don't understand why the question would be considered a micro optimization. It's just a novice question about how memory is used in the browser when multiple invocations of functions take place in between GC cycles. And it's just an example of what I've been examining, and does not depend on indexedDB at all, nor whether or not memory leaks really exist in properly coded applications. The description I provided likely made it confusing.
If a function employs local variables to retrieve an array of data objects from an indexedDB object store and in the transaction.oncomplete handler passes reference to that area of memory to another function that uses it to build a document fragment and replace a DOM node what happens to the data? Two functions have reference to the array and one to the fragment. If the references are manually broken by setting the variables that pointed to them to null (and even if not set to null), eventually the GC will release that memory. But, if the user clicks through rapidly, repeatedly invoking these functions in a short interval of time, that is, between GC cycles, will each invocation allocate a new area of memory for the data array and fragment, such that in between the GC cycles, there could be ten sets of data areas held in RAM waiting to be relased? If the array was held in a property of the function that retrieves it, would each invocation re-use that same area of memory or would the function property simple change its reference to a new area of memory holding the new array and breaking reference to the area of memory holding the previous array, but there would still be ten sets of data areas in between GC cycles?
As I wrote before, I was wondering if there was a way to re-use the same memory area for each invocation. If not possible and if there would always be several sets of data held in RAM waiting to be released between GC cycles, it may be beneficial to retain reference to the current data set and use it to reduce the amount of work performed by the browser to save the current state, which, in itself is an entriely separate issue but one that depends on how the memory is used by the browser.
When I observe snap shots of the memory in Firefox developer tools, memory use grows as I step through these data sets, repeatedly retrieving new data and building a new fragment to replace the DOM node; but the amount of that data is relatively small and it may just build up until the GC cycle runs. From this observation, it appears that each invocation uses a new area of data and breaks the reference to the previous area of data. Therefore, maintaining a reference to the current data set is not a memory issue because there are always many such memory areas held in RAM anyway in between GC cycles.
Nonetheless, I must have an issue of some sort because after adding 100 data packets, and navigating up an down them through Next / Previous buttons, the data usage continues to grow and nearly all in the domNode section. It starts out at 7MB total, 6MB in domNode and 5MB of that in #document. #document remains at 5MB but domNode grows to at least 150MB as do nothing but move up and down the records, retrieving data, building and replacing nodes but never making an edit to the data; and never having more than one node for it is always replacement of exactly the same size because in this test the 100 data packets are identical copies. So, just getAll, build a fragment, replace a DOM node, over and over again.
Thank you.
Consider JavaScript code below. I am creating array of let's say 4 elements and then immediately delete reference to it. When will garbage collection happen? I know it is specific to language implementation, but we have not that many JavaScript engines.
Edit: it is the simplest possible case, but it interests me because garbage collection causes audible glitches in some web audio applications.
var a = [1, 2, 3, 4];
a = null;
// other code
Update:
Javascript and Garbage collection does not explain the sequence of events and how it is triggered. I don't want to control garbage collection. I need better understanding to design better code.
There are many ways GCs can be triggered
allocation-triggering: there is no more room in the allocation buffers/young generation/howeveritiscalled and a GC is required to free up objectsThis gets a bit more complicated in a mixed GC/manual allocation environment. malloc wrappers might need to trigger GCs too since javascript can hold onto manually allocated resources.
[in browsers] when a tab/window gets closed/replaced on the assumption that there is lots of easy-to-collect garbage at that point
time-triggered by heuristics for incremental collections to meet pause time goals
privileged javascript may be able to trigger collections directly
as last-ditch effort by various non-GC-managed components if they run out of native resources (file handles, virtual address space) in the hope that GC objects awaiting finalization were holding onto them
There probably are other reasons that I currently can think of. It's generally not something you should concern yourself with.
If you want to keep GCs low you need to keep your object allocation rate low. E.g. some algorithms can benefit from pre-allocated buffers on which they perform their work. The effectiveness of that strategy depends on whether the javascript runtime has escape analysis and how effective it is at avoiding short-lived allocations in the first place. And on whether the collector is generational. A generational collector suffers a lot less from rapid, short-lived allocations.
It's a good approach to delete the references of objects that are no longer in use. Many (almost all) javascript engines use Mark and Sweep approach. If you are deleting a reference to an object and it has no other references, it will probably be collected in the next Mark and Sweep Cycle.
Garbage collection is a cyclic approach that happens in regular intervals in few engines. Some engines say they do GC in an efficient manner but, there are no valid documentation available.
I don't know too much about the JavaScript garbage collector, just that it attempts to manage references so that unreferenced objects can be periodically purged from memory. I was thinking about something that I thought might improve performance if it was feasible by the language implementers.
It would go something like this. In a file add a line:
"no gc";
This is similar to the use strict setting. It would mark everything defined in the file as not for garbage collection. I'm thinking this would be used in libraries like jQuery and underscore. All of the helper methods would be marked and stored in a separate area of memory that is not managed by the GC.
While I know this might end up keeping around stuff that is not ever used; it would at least isolate it from periodic GC process. So while we perhaps gobble up some extra memory, we at least lighten the load of GC processing.
I apologize for the naivety of this suggestion as I have never implemented GC. I am just wondering if this idea is feasible or if JavaScript somehow does this already.
if you want to keep them as cache then you have global scope.
In browser global scope is window,
hence consider if you dont want object X to never get garbage collected then simply you can write
window.nogc = X;
since window which is global scoped ,will be never garbage collected so its child references also wont be garbage colleted until we explicitly make it.
Garbage collection only runs when the thread is free. Nothing would be saved because GC only occurs when the system isn't busy.
So no, this isn't possible.
You can ensure that an object does not get collected by referencing it from a GC root, but not that it doesn't get processed by the GC.
The reason is that GC in JS VMs is usually implemented via Mark-and-Sweep, or a method that is functionally equivalent. The basic premise is that the GC goes through a cycle that goes like this:
The GC marks all objects in the heap as being "potentially available for release". This is usually done by a flag toggle which changes the interpretation of the existing marks on objects from meaning "need to keep" to "safe to release". So no actual iteration over the objects occurs at this stage. Telling the GC to "not mark" certain objects would actually require extra operations, not less.
The GC starts at the GC roots, and traverse through the reference tree, changing the mark of objects from "safe to release" to "need to keep". This is the "Mark" phase. GC roots can be global objects, the currently executing stack, pending callbacks on the event loop, etc. The tree-traversal itself can be done in various way as well, with DFS being the simplest.
The GC goes over all objects in the heap, and removes any that is still marked "safe to release". This is the "Sweep" phase. Many optimizations exist in this phase, which allows the GC to free memory used by a group of objects in a single operation. Nevertheless, this requires at least some level of iteration, over groups of objects, if not over objects themselves.
Now here's the issue with setting a "non-GC" arena: Suppose that an object in your "non-GC" arena was to reference a regular object. During the "Mark" phase, if that object is not marked, it would be released. That means that all of your "non-collectible" objects need to be GC roots in order to "keep" regular objects to which they refer. And being a GC root offers no performance advantage over being directly referenced by a GC root. Both must equally participate in the "Mark" phase.
The only alternative is for your non-collectible object to not be able to strongly reference collectible objects at all. This can be achieved by having your own binary heap, rather than using native JS objects. The binary data would not be interpreted as references, and the heap object would finish its marking phase in a single operation. This is what asm.js does: It preallocates a large array to act as its internal heap. To the VM, the entire array counts as one big object, and therefore no garbage collection is done on any data structures that are encoded within it. Using this method does have the flaw that you need to encode all of your objects and data structures into the heap's binary format, and decode them when you want to use them. When working with asm.js, this is handled by the compiler.
in JavaScript if you want to kill a object, you have to delete all the references.
let's say we have a object like this:
var myobj={ obj : {} };
and we want to GC the obj object, we have to do this:
myobj["obj"] = null;
delete myobj["obj"];
but if you define another variable referenced to that object, it won't be killed with those line. for instance if you do:
var obj = myobj.obj;
if you really want to delete the object, you have do the same for this variable:
obj = null;
delete obj;
then if there is no reference it would be killed.
in other word if you want to prevent your object from GC, create a reference some where and keep it private.
When I remove items from an array in javascript using the splice method, an array of the removed items are returned.
var a = [{name:'object1'},{name:'object2'},{name:'object3'}];
// a.splice(0,2) -> [{name:'object1'},{name:'object2'}]
// Where do these guys live now? Are they really gone?
Do I then need to call 'delete' on those returned objects to make sure they are taken out of memory? Does the garbage collector just handle this? Can I trust that?
The objects are 'gone' (from your perspective) and the GC will actually free the memory when it deems appropriate. JavaScript does not give you explicit control over garbage collection.
If you're concerned about performance, it's generally better (after profiling, of course) to focus on saving allocations rather than worrying about when exactly things will get GC'd, since that behavior will change depending on which JS engine you're on.
I have a very large collection of objects in node.js (millions) that I need to keep in memory for caching purposes (they are maintained in several global hash objects). Each hash collections stores about 750k keys.
In order to keep GC to a minimum, I want to find out the best way to store these items. Would it be better to split these items into 100s of thousands of hashes? Should I maybe not use hashes at all? Is there any way to keep them off the heap completely so they never are examined by GC (and if so how would I do so)?
There is no public API to control garbage collection from JavaScript.
But GC has gone a long way over the years. Modern GC implementations will notice that some objects live long and put them into a special "area" which will be collected only rarely.
How this exactly works is completely implementation dependent; every browser does it's own thing and usually, this also often changes when a new browser version is released.
EDIT The layout on memory and the organization is completely irrelevant. Modern GCs are really hard to understand in detail without investing a couple of weeks reading the actual code. So what I explain now is a really simplified picture; the real code will work different (and some GCs will use completely different tricks to achieve the same goal).
Imagine that the GC has a counter for each object in which it counts how often it has seen it in the past. Plus it has several lists where it keeps objects of different age, that is with objects whose counters have passed certain thresholds. So when the counter reaches some limit, the object is moved to the next list.
The first list is visited every time GC runs. The second list is only considered for every Nth GC run.
An alternate implementation might add new objects to the top of the "GC list" and for every GC run, it will only check N elements. So long living objects will move down the list and after a while, they don't be checked every time.
What this means for you is that you don't have to do anything; the GC will figure out that your huge map lives a long time (and the same is true for all objects in the map) and after a while, it will start to ignore this data structure.