CPU vs Memory usage (theory)

2019-06-07 05:19发布

问题:

I found some interesting post about memory usage and CPU usage here on Stack Overflow, however none of them had a direct approach to the apparently simple question:

As a generic strategy in a JavaScript app, is it better in terms of performances to use memory (storing data) or CPU (recalculating data each time)?

I refer to javascript usage in common browsers environment (FF, Chrome, IE>8)

Does anybody have a more direct and documented answer to this?

--- EDIT ---

Ok, I understand the question is very generic. I try to reduce the "scope".

Reading your answer I realized that the real question is: "how to undestand the memory limit under which my javascript code still has good performances?". Environment: common browsers environment (FF, Chrome, IE>8)

Functions I use are not very complex math functions, but can produce quite a huge amount of data (300-400kb) and I wanted to understand if it was better to recalculate them every time or just store results in variables.

回答1:

Vaguely related - JS in browsers is extremely memory hungry when you start using large objects / arrays. If you think about binary data produced by canvas elements, or other rich media APIs, then clearly you do not want to be storing this data in traditional ways - disregarding performance issues, which are also important.

From the MDN article talking about JS Typed Arrays:

As web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data.

Here's a JS Perf comparison of arrays, and another looking at canvas in particular, so you can get some direct examples on how they work. Hope this is useful.



回答2:

It's just another variation on the size/performance tradeoff. Storing values increases size, recalculating decreases performance.

In some cases, the calculation is complex, and the memory usage is small. This is particularly true for maths functions.

In other cases, the memory needed would be huge, and calculations are simple. This is particularly true when the output would be a large data structure, and you can calculate an element in the structure easily.

Other factors you will need to take into account is what resources are available. If you have very limited memory then you may have no choice, and if it is a background process then perhaps using lots of memory is not desirable. If the calculation needs to be done very often then you are more likely to store the value than if it's done once a month...

There are a lot of factors in the tradeoff, and so there is no "generic" answer, only a set of guidelines you can follow as each case arises.