Search code examples
javascriptv8

Is JavaScript standby functionality stored in RAM or the hard drive?


This is a bit of a strange question where I do not know enough to possibly ask it correctly, so I will do my best (googling for a worthwhile result has proven difficult):

  • You write a Javascript program
  • V8 (or other interpreters) compiles your script (I understand WHICH interpreter is running vastly changes the results of the answer to this, so let's stick with V8)
  • Your Javascript could be a formidably large footprint of executable code
  • Does V8 keep any routines that are not in use on the hard drive? Or does the Javascript interpreted commands stay completely in RAM?

I was wondering this because it would seem unfortunate for a massive JS program to eat into the available RAM allotment a browser gives if the complexity of the JS program was overtly large.

I know this gets into: if you have such a huge program you're doing it wrong, but I like to push things where I can and if I get a better understanding of how this all works, I can make better decisions :)


Solution

  • (V8 developer here.) Short answer: no, V8 does not swap any unused things (code or otherwise) to disk at runtime.

    Executable code is typically not the biggest consumer of memory we see in V8, it tends to be dwarfed by (non-code) data. Still, the amount of code can certainly be significant; one of the reasons why V8 switched its first (unoptimized) execution tier from a compiler to an interpreter a few years ago was because that interpreter's bytecode is much smaller than the earlier non-optimizing compiler's machine code it replaced. When a function is optimized, it's still compiled to machine code; but since typically only relatively few functions get optimized, that usually only takes up a low single-digit percentage of overall memory.

    In embedders that support it (like Chrome), V8 does support caching certain things between runs, including code. That's a performance optimization: some work can be avoided if you visit the same website multiple times. This mechanism doesn't temporarily free up any memory, and it's not supposed to.

    Generally, it's not the job of individual applications to swap things to disk -- it's the job of the operating system. When all running applications combined use more memory than is available, then the kernel will pick some "pages" (chunks of memory) and write them to disk. Applications don't notice any of that (except a massive loss of performance when those pages are needed again) and don't have to do any work to support it. So this part of the answer applies not just to V8, but also to other JavaScript engines, and in general to all other programs you may run on your computer.