Partial garbage collection possible? (server-side JS)

Suppose the server-side JavaScript environment that provides this function:

var parseIsoDuration = /... complex regex .../ function dateDiff(date, isoDurationStr){ var duration = parseIsoDuration.exec(isoDurationStr); return timeLibrary.add(date, duration); } 

This function will be called externally, for hundreds of dates, but basically for the same ISO duration. Since RexExp analysis is not a cheap operation, an application-level cache can be implemented:

 var parseIsoDuration = /... complex regex .../ var durationCache = {} function dateDiff(date, isoDurationStr){ var duration; if (durationCache[isoDurationStr] === undefined){ duration = parseIsoDuration.exec(isoDurationStr); durationCache[isoDurationStr] = duration; } else { duration = durationCache[isoDurationStr]; } return timeLibrary.add(date, duration); } 

Problem: the server can run for a year in a row, and the cache object never goes beyond. If a function is called with a large number of lines of ISO duration, the cache will grow over time and will never reduce its size.

Is there a way to tell V8 that it can clear the “old” entries from the cache object as needed (i.e., it got too big)? Or at least make it clear as necessary? (The decision may depend on the features of ES6 / 7)

ES6 WeakMaps sound interesting, but they only accept objects as keys. Wrapping a string in an array to make it an object will not work, because it will again lead to another object. I need something like Symbol(str) , but this returns an identical reference for two identical inputs ( Ref(str) === Ref(str) ).

edit: Actually, Symbol.for("str") === Symbol.for("str") , but it is not accepted as the WeakMap key.

I’m also not sure that when records will garbage in the case of WeakMap, it can be more or less immediately, because the link will not refer to the object immediately after it is added to WeakMap. So double no.

Cancellation of individual keys will require additional consideration when adding and some algorithm to determine a reasonable TTL.

Do I need to cache RegExp results? Is there a built-in cache? For literal expressions, or if they are only created using the constructor or both?

0
javascript garbage-collection caching v8
04 Sep '15 at 12:10
source share
1 answer

What are you talking about sounds like Java SoftReference , and no, there is nothing like that in v8. Instead, you must manage the cache yourself or use one of the modules, for example lru-cache

+1
Sep 04 '15 at 12:28
source share



All Articles