In JavaScript, you can't directly access the amount of memory consumed by your code or variables using a standard API. JavaScript does not provide a built-in method to check the memory consumption of objects or variables. However, you can make use of browser-specific tools and techniques to monitor memory usage for debugging purposes.
Here's how you can do that
- Performance API (Chrome and Firefox): You can use the Performance API to measure memory usage in Chrome and Firefox. The
performance.memory
object provides information about memory consumption.This will log the used and allocated memory in megabytes. Keep in mind that this is browser-specific and may not work in all browsers.if (window.performance && window.performance.memory) { const memoryInfo = window.performance.memory; console.log(memoryInfo.usedJSHeapSize / (1024 * 1024) + " MB used"); console.log(memoryInfo.totalJSHeapSize / (1024 * 1024) + " MB allocated"); }
- Chrome DevTools:
Chrome DevTools provides a more powerful way to inspect memory usage. You can use the "Memory" tab to profile memory usage in your JavaScript application. This is a better option for detailed memory analysis. - Performance.now() for Tracking Changes:
While you can't directly measure memory usage, you can use theperformance.now()
method to track how memory usage changes over time by taking memory measurements at different points in your code.const startMemory = window.performance.memory.usedJSHeapSize; // Execute your code const endMemory = window.performance.memory.usedJSHeapSize; console.log(`Memory change: ${endMemory - startMemory} bytes`);
Third-party libraries:
There are third-party libraries likememory-stats.js
that provide a simple way to monitor memory usage in JavaScript. You can include this library in your project and display memory statistics on your page.
Below is another example for refreshing Advertisement on the browser
// request garbage collection for the browser if (typeof window.gc === 'function') { window.gc(); } // check memory used and enable/disable refreshing banner ads() if (window.performance.memory.usedJSHeapSize > window.performance.memory.usedJSHeapSizeLimit*0.25) stopRefreshBannerAds(); else enableRefreshBannerAds();