Перейти к содержимому

Browser cache disk capacity какое значение ставить

  • автор:

Caching

Tanmay Garg

Ever tried to improve the performance of an application? The first and foremost thing that comes to mind is caching. But there are several different ways and layers of caching. It’s important to understand the PROS and CONS of each approach and which can be combined. Often it’s dependent on the application-specific requirement and ease of implementation.

You can do caching both at the `front-end` and the `back-end`.

Frontend

Frontend caching refers to the use of caching techniques on the client side, rather than on the server side. Often developers aren’t aware of the frontend caching or ignore it. Frontend caching can be very powerful and is the easiest to implement. This can help to improve the performance of a website or web application by reducing the amount of data that needs to be transferred over the network. And when millions of users are there the burden of caching is shifted to that millions of users so it can scale infinitely.

Some common techniques for frontend caching include:

  1. In-memory caching: This involves storing frequently accessed data in the computer’s memory (RAM) so that it can be quickly retrieved without the need to make a network request.
  2. Disk caching: RAM gets cleared on closing the browser. So to have the cache valid across different sessions one can use either local storage, session storage, or index DB.

Here are some examples of size limitations for different types of browser caching in some popular browsers:

  • In-memory cache: 512MB
  • Disk cache: There is no explicit limit on the size of the disk cache in Chrome. The size of the cache will depend on the available disk space on the device.
  • In-memory cache: 50MB
  • Disk cache: The size of the disk cache in Firefox is configurable through the “browser.cache.disk.capacity” preference, which has a default value of 15360KB (15MB).
  • In-memory cache: 50MB
  • Disk cache: The size of the disk cache in Edge is configurable through the “browser.cache.disk.capacity” preference, which has a default value of 15360KB (15MB).
  • In-memory cache: The size of the in-memory cache in Safari is determined by the available RAM on the device, and there is no explicit limit on the size of the cache. The cache uses a least recently used (LRU) eviction policy to manage its size.
  • Disk cache: The size of the disk cache in Safari is determined by the available disk space on the device, and there is no explicit limit on the size of the cache. The cache uses a least recently used (LRU) eviction policy to manage its size.

As you can see Firefox, and Edge is useless with such low limits. And disk cache has a greater limit than in-memory. Chrome being the most widely used, we are good. The size limit of 512MB for chrome is shared by all origins. When it gets full it uses the least recently used (LRU) eviction policy to clear the cache.

IN MEMORY CACHING

First, try to understand what does in memory means. Whenever you open up a website you see so many things, text, audio, and video. Definitely, they would need to be stored somewhere to display to you, they are stored directly in RAM hence called in-memory.

By default, most modern web browsers will cache a variety of resources that are requested and received during the browsing session. This includes resources such as HTML files, CSS stylesheets, JavaScript scripts, images, and other media files.

The specific resources that a browser will cache and the rules for caching them are usually determined by the HTTP headers and caching directives that are sent by the server along with the resource. For example, the “Cache-Control” header can be used to specify whether a resource should be cached, for how long it should be cached, and under what conditions it should be revalidated.

So how can I do in-memory caching except for the default behavior?

  1. Using Cache-Control headers

Using this you can configure and change the default behavior of in-memory caching. Let’s say we want to cache all ‘GET’ calls in-memory

Cache-Control is an HTTP header that can be used to control how and when a client caches particular resources. The Cache-Control header can be set on the server, and it specifies directives that tell the client how long a resource can be cached and under what conditions it can be reused.

For example, the following Cache-Control header specifies that the client can cache the response for a maximum of one hour.

This means that the client can reuse the cached response for any subsequent requests for the same resource within the next hour.

Here is a list of some common values for the “Cache-Control” header:

  • “public”: This value indicates that the resource can be cached by any cache, including caches that are shared by multiple users.
  • “private”: This value indicates that the resource can only be cached by a cache that is specific to a single user.
  • “no-cache”: This value indicates that the cache must revalidate the resource with the server before using it.
  • “no-store”: This value indicates that the resource should not be stored in the cache.
  • “max-age”: This value specifies the maximum amount of time that the resource can be stored in the cache before it must be revalidated. The value is specified in seconds.
  • “s-maxage”: This value is similar to “max-age,” but it only applies to shared caches (caches that are shared by multiple users).
  • “must-revalidate”: This value indicates that the cache must revalidate the resource with the server before using it, even if it has not expired.
  • “proxy-revalidate”: This value is similar to “must-revalidate,” but it only applies to proxy caches (caches that are used by a proxy server).

Pros:

It is easiest to implement like just a single line needs to be added on the server side to tell the browser to cache all GET calls.

Ultra-fast. Response time of 1–2 ms.

Cons:

It cleared on closing the browser.

Size is limited

Can’t cache ‘POST’, ‘PUT’, and ‘DELETE’ calls — This is on purpose because they are data modification calls, but there can be a rare scenario where you are using say ‘POST’ call as a ‘GET’ call since the parameters are very high in number and hence needs to be passed into the body. So ideally you would like to cache such a POST call but Cache-Control header won’t be able to help you with that.

2. Manual Caching

There are some limitations of Cache-Control headers and you don’t have full control. To have full control of what and how you want to cache you can cache manually.

Ex — you can even cache a POST call, though that would be a bad idea.

Here is an example of how you might implement in-memory caching in JavaScript:

DISK CACHING

You can use the localStorage API to store values in the user’s web browser so that they can be accessed even after the page has been refreshed. Here is an example of how you might use localStorage to cache API responses:

Of course, this is just a simple example to illustrate the concept. In a real-world application, you would need to consider factors such as cache expiration and data invalidation, and you would also need to handle errors and edge cases.

Therefore it’s best to use a sophisticated caching library or framework to manage your cache, rather than implementing it by yourself.

Axios is a popular JavaScript library for making HTTP requests. It is often used in combination with frontend frameworks such as React or Angular to fetch data from APIs or other web services.

To use Axios for caching, you can use the axios.create() method to create a new instance of the axios object, and then pass in a cache option with a value of true . This will enable the built-in caching feature in Axios, which uses the ETag header to determine whether a response can be cached and whether it is still valid.

Here is an example of how you might use Axios with caching enabled:

This will enable the built-in caching feature in Axios, which will automatically store the responses to successful GET requests in a local cache. Subsequent requests to the same endpoint will be served from the cache unless the response has changed (as determined by the ETag header).

In addition to the built-in caching feature, Axios also allows you to use custom caching adapters to implement more advanced caching strategies. An Axios adapter is a function that intercepts the outgoing request and incoming response and allows you to modify or manipulate the data in some way.

To use a custom caching adapter with Axios, you can use the axios.create() method to create a new instance of the axios object, and then pass in an adapter option with a reference to your custom adapter function. Your adapter function should accept a config object as an argument, and return a Promise that resolves with the modified config object.

Here is an example of a simple caching adapter that uses the lru-cache library to implement an in-memory LRU (least recently used) cache:

Another very simple to use adapter is axios-cache-adpater

To use axios-cache-adapter to cache requests, you need to install the package and create a new instance of axios with the cache adapter. Here is an example:

In the example above, we create a new instance of axios using the axios-cache-adapter package. Then, we configure the cache adapter to set the maximum cache size to 15 and exclude query parameters from being considered when caching requests.

Finally, we use the api instance to make a GET request to the specified endpoint. If the request is successful, it will be cached according to the configuration provided to the cache adapter. You can also use the api instance to make other types of requests (e.g. POST, PUT, DELETE) and they will be cached if the request is successful.

Note that the axios-cache-adapter package uses an in-memory cache by default, which means that the cached data will be lost when the application is restarted. If you want to persist the cached data, you can use one of the storage adapters provided by the package (e.g. local storage, indexedDB) or implement your own storage adapter.

Local Storage:

To use local storage with axios-cache-adapter , you need to install the axios-cache-adapter-localstorage package and create a new instance of axios with the local storage adapter. Here is an example:

local storage has limited capacity, so you should be careful not to exceed the available space when using this adapter.

Indexed DB:

To use indexedDB with axios-cache-adapter , you need to install the axios-cache-adapter-indexedDB package and create a new instance of axios with the indexedDB adapter. Here is an example:

The cached data will be stored in indexedDB and will be available even after the application is restarted.

Note that indexedDB is only available in modern browsers, so if you need to support older browsers you will need to use a different storage adapter or implement your own storage adapter.

Chrome and most of the chromium-based browsers allows 80% of the disk space to be used and from that 75% can be used by each origin. That means, If you have a disk space of 100GB then 80GB can be used to store data in indexedDB and from that 60GB can be used by single origin.

Also, Firefox allows 2GB data to be stored by each origin and Safari allows 1GB per origin.

Conclusion:

Using an external library to cache is easiest. Using IndexedDB for caching is best since it has no storage limit, local storage is limited to a meager 10MB, and In-memory cache is not persisted and cleared on browser refresh.

PROS and CONS of frontend caching:

Pros:

  • Allows for faster access to cached data, as it is stored in the user’s browser and can be accessed directly without making a request to the server.
  • Can reduce the server load as the amount of data transferred between the server and the client is reduced, which can improve the overall performance of the application.
  • Is easy to implement and does not require any changes to the server-side code.

Cons:

  • Does not cache data for all users, as each user will have their own cache stored in their browser. So the first request will be slower.
  • Is not effective for caching large amounts of data, as the available cache space in the user’s browser is typically limited.
  • Users can always clear the cache manually even if stored in Indexed DB or local storage.

Backend Caching:

  1. In-memory caching: This involves storing the cached data in memory on the server, which allows for fast access to the data but can cause data loss when the server is restarted. In-memory caching can be implemented using a library like node-cache or lru-cache .
  2. File-based caching: This involves storing the cached data in a file on the server, which allows for persistence of the data but can be slower than in-memory caching. File-based caching can be implemented using a library like node-cache or fs-extra .
  3. Distributed caching: This involves storing the cached data in a distributed cache (e.g. Redis, Memcached) that is shared across multiple servers, which allows for high performance and scalability but can be more complex to implement and maintain. Distributed caching can be implemented using a library like node-cache-manager or node-cache-manager-redis.
  4. In-memory caching using node-cache :

In the example above, we create a new NodeCache instance and use it to set and get values in the cache. The stdTTL option is used to specify the time-to-live (TTL) for the cached values, in seconds.

2. File-based caching using fs-extra :

In the example above, we use the fs-extra package to create a cache directory and set and get values in the cache. The values are stored in JSON files in the cache directory, and are accessed using the specified key.

3. Distributed caching using node-cache-manager-redis :

In the example above, we create a new cache instance using the node-cache-manager and node-cache-manager-redis packages. We configure the cache to use the Redis store and specify the host, port, and database number for the Redis server. Then, we use the cache instance to set and get values in the cache.

Оптимизация Mozilla FireFox: снижаем потребление оперативной памяти, ускоряем загрузку браузера и пр.

Я уже писал о том как ускорить загрузку страниц в Mozilla FireFox методом редактирования различных настроек с помощью about:config, однако помимо этого есть еще кое-что, что не мешало бы подкрутить в этом браузере.

ram firefox

Многие знают, что FireFox будучи напичкан разными плагинами (и даже не будучи ими напичкан) жует относительно много оперативной памяти как в свернутом, так и в развернутом виде.
Однако есть возможность провести некоторую оптимизацию, которая не только несколько снизит потребление ресурсов компьютера, но и сделает работу браузера несколько шустрее и адекватней.

Уменьшаем количество потребляемой оперативной памяти Firefox

Начнем с оптимизации потребления памяти.
Итак, поехали:

  1. Запускаем наш браузер Mozilla Firefox
  2. Набираем (именно набираем, а не копируем) в адресной строке (это там, куда мы вводим, например sonikelf.ru) about:config и, согласившись быть осторожными, попадаем на страницу настроек браузера
  3. Находим в списке настроек параметр browser.sessionhistory.max_total_viewers и выставляем его значение 0
  4. Далее (нажав правой кнопкой мыши и выбрав из выпадающего списка «Создать—Логическое«) надо создать параметр с названием config.trim_on_minimize и значением true
  5. Закрываем страницу настроек и перезапускаем браузер

Двумя этими параметрами мы внесли изменения в подсистеме кеширования данных, чем снизили потребление объема оперативной памяти в свернутом режиме (значение config.trim_on_minimize отвечает за выгрузку Firefox в файл подкачки, пока, собственно, браузер свернут) , а так же подковыряли один важный параметр, изменивший потребление оперативки в ходе путешествия по интернету.

Дело в том, что browser.sessionhistory.max_total_viewers отвечает за количество отведенной оперативной памяти в которую откладываются посещенные нами страницы. Сделано это для того, чтобы при нажатии кнопочки «Назад«, браузеру не приходилось подгружать страницу заново целиком из интернета или из кеша на жестком диске, что ускоряет путешествие по посещенным уже сайтам с использованием вышеупомянутых кнопок «Вперед-Назад«. У меня есть вполне себе обоснованное мнение, что и без этой приблуды переход достаточно шустр, так что можно оное отключить, ибо оно потребляет оперативную память по совсем уж бессовестной схеме:

оперативная память и firefox

Соответственно, присвоив вышеуказанному значению 0 (вместо стандартного -1) мы отключили работу этой функции и тем самым спасли любимые мегабайты оперативной памяти, которые неизменно откусывались в ходе серфинга по сайтам.

Далее хочется отметить, что огромный кусок потребление ресурсов отводится не столько самому FireFox‘у, сколько навешанным на него плагинам и расширениям, а посему давайте проведем небольшую оптимизацию в этой области. Для этого открываем «Инструменты — Дополнения» и смотрим, что же у нас там установлено:

  • В первую очередь стоит удалить всё чем Вы точно не пользуетесь или предназначение чего Вам неизвестно. Для этого попросту выберите пункт «Удалить» напротив того или иного расширения
  • Далее я рекомендую использовать кнопку «Отключить» напротив тех плагинов, которые Вы ныне не используете в данный момент, но которые Вам периодически бывают нужны. Как пример, это может быть, скажем, VideoDownloadHelper, которым Вы порой наверняка скачиваете музыку и видео, но делаете это далеко не регулярно (например я использую этот плагин от силы раз в неделю-две, а остальное время он у меня выключен) . Поступите так со всеми неиспользуемыми ныне расширениями и попросту включайте их по мере надобности

Теперь, что касается «Плагинов» (именно плагинов, а не дополнений) , ибо их тоже надо бы привести в порядок, что, к слову, далеко не все делают попросту не зная о их существовании. Для того, чтобы ими управлять переходим на вкладку «Инструменты — Дополнения — Плагины«.

отключение плагинов firefox

Здесь, пожалуй, стоит отключить всё кроме Shockwave Flash и Java TM Platform (хотя оный плагин бывает нужен далеко не всегда и не всем) . Остальное, как правило, понакрученые разными приложениями надстройки, смысла в которых решительно никакого нет. Как вариант еще можно оставить Adobe Acrobat (отвечает за открытие PDF-файлов напрямую в Firefox) , но лично я предпочитаю пользоваться одноименным приложением, а не плагином.

Закончив работать с плагинами и расширениями перезапустите браузер.

Перейдем к дальнейшей настройке потребления памяти, а именно, на сей раз, к работе с кэшем как в оперативной памяти, так и на диске. Сие настройки довольно гибкие и напрямую влияют на пережевываемую браузером память и место. Рассказываю, что к чему:

    • Снова открываем любимый нами about:config. О том как это сделать я писал выше.
    • Вбиваем в строке «Фильтр» слова browser.cache и видим перед собой примерно вот такой список:

    firefox

      • Здесь нас интересуют параметры browser.cache.memory.enable и browser.cache.memory.max_entry_size
      • Первый, а именно browser.cache.memory.enable включает-отключает использование оперативной памяти в целях кэширования содержимого загруженных страниц, а именно изображений, элементов пользовательского интерфейса и тп. Выставив здесь значение false Вы отключите использование оперативной памяти для этих целей, что снизит потребление оной браузером, однако напрямую скажется на производительности Firefox. С другой стороны, Вы можете попросту ограничить этот кэш, задав параметру browser.cache.memory.max_entry_size значение из таблицы ниже:

      оперативная память firefox, таблица потребления

      Где первый столбец показывает сколько памяти будет выделяться под нужды кэша, а второй соответствующее значение, которое указывается для параметра browser.cache.memory.max_entry_size. Т.е, если, допустим, Вы хотите, чтобы под кэш выделялось не более 64 MB, то задайте параметруbrowser.cache.memory.max_entry_size значение 4096.

      К слову, здесь же Вы можете настроить использование кэша жесткого диска для тех же целей. За оный отвечают параметры browser.cache.disk.enableи browser.cache.disk.capacity. У меня это кэширование отключено, но при этом оперативной памяти в системе 8 ГБ, а посему включено кэширование в память и соответственно для фаерфокса выделено дофига и больше оперативки, ибо я сторонник повышенной производительности. Что Вам важней и почему думайте сами. В принципе можно отключить и тот и тот кэш.

      Закончив редактирование, закройте конфиг и перезапустите браузер.

      С оперативной памятью пока всё. Перейдем к настройкам скорости загрузки браузера и его шустрости в целом, ибо некоторые жалуются на долгий запуск Firefox и его периодические подвисания.

      Оптимизация скорости загрузки Firefox, а так же стабильности и скорости работы

      Как правило, долгий запуск и излишняя тормознутость/подвисания, связаны со слабой дисковой подсистемой и чрезмерно раздутым (или кривовато настроенным) кэшем. Кэш мы с Вами частично уже настроили (и частично еще настроим) , а вот всё остальное надлежит поковырять. В частности, мы сделаем несколько полезных настроек браузера, которые несколько ускорят его загрузку и скорость работы в целом.

      Для начала рекомендую таки немного ускорить работу дисков, для чего проведите несколько настроек по оптимизации оных, о чем я писал в статье «Немного настроек для оптимизации работы жесткого диска«, а так же сделайте дефграментацию.

      Далее, лично я рекомендую перенести firefox на диск C:/, а именно в его корень (т.е не в какую-то из подпапок, аля Program Files, а именно простоC:/firefox) . Если мне не изменяет память, то переустановка браузера для этого необязательна, — просто используйте правую кнопку мышки и команду «Вырезать — Вставить«. При необходимости создайте новый ярлык (старый может не работать из-за изменения пути) , что делается все той же правой кнопкой мышки на firefox.exe и пунктом «Создать ярлык«. Если C:/ не является самым шустрым диском в системе и есть физически более быстрые, то перенесите firefox туда.

      Перейдем к настройкам. Дело в том, что при запуске, браузер проверяет уж больно много всего, что замедляет загрузку. Посему давайте это уберем. Для оного запускаем Firefox, открываем «Инструменты — Настройки«. В появившемся окне настроек переходим на вкладку «Дополнительные» и подвкладку «Общие«.

      firefox настройки, ускорение загрузки браузера

      Здесь я рекомендую снять последние 3 галочки, а именно «Всегда проверять при запуске, является ли Firefox браузером по умолчанию«, «Отправлять сообщения о падениях» и «Отправлять данные о производительности«.

      ускорение запуска firefox, настройки

      Далее переходим на подвкладку «Сеть«. Здесь ставим галочку «Отключить автоматическое управление кэшем» и задаем какое-либо свое значение.

      firefox настройки, ускорение загрузки браузера

      На подвкладке «Обновления» отключаем проверку обновлений Firefox (это всегда можно сделать вручную, используя «Справка — О firefox —Проверить наличие обновлений«) и плагинов поисковых систем, т.е снимаем галочки с соответствующих пунктов. В общем-то можно так же отключить и проверку обновлений дополнений, благо оные проверяются при каждом обновлении браузера. Здесь думайте сами как Вам удобней (у меня отключено) .

      Послесловие

      Как-то так. Надеюсь, что Ваш любимый FF после этого стал бегать пошустрее и кушать поменьше.

      PS: Статья написана 7 Февраля 2009. Глобальное обновление 22 октября 2011.

      Как изменить размер кэша Firefox

      Разработчики часто дают возможность пользователю корректировать глубинные настройки системы, дабы человек мог подстроить ее под свои предпочтения и требования. Сегодня мы поговорим о том, как увеличить кэш в Мозиле, в процессе повествования также рассмотрим характерные особенности процедуры и пошаговую инструкцию.

      Инструкция

      Существует несколько способов увеличения кэша, но мы рассмотрим максимально простой и регламентированный самими разработчиками. Делается все непосредственно из окна настроек Фаерфокса. Ознакомимся с процедурой более детально.

      Настройка

      Здесь используется только встроенный функционал интернет-обозревателя, а пошаговая инструкция по претворению задуманного в жизнь уже ждет:

      1. Запускаем Мазилу и вводим в адресную строку запрос about:config.
      2. Кликаем на синюю кнопку на странице с предупреждением, ведь оно нам ни к чему.Переход на страницу about-config в браузере Mozilla Firefox
      3. В строку поиска вводим browser.cache.disk.capacity.
      4. Кликаем по соответствующему пункту ПКМ и выбираем первую опцию из контекстного меню.Изменение размера кэша Firefox
      5. Вводим новое значение, которое записывается в кбайтах.
      6. Закрываем окно параметров.

      Дополнение

      Это основной способ, как добиться увеличения кэшового пространства в браузере Фаерфокс. Он отличается своей простотой и удобством. Но возникает иной вопрос: нужно ли это действие в принципе. Ведь стандартные параметры «Огненной лисицы» рассчитаны на стабильный и плавный интернет-серфинг. Но если все же подлагивания случаются, то наша инструкция поможет их избежать.

      Как заставить Firefox жрать меньше памяти

      Как заставить Firefox жрать меньше памяти
      У меня раньше этот браузер отжирал по 200-300 мегабайт, сейчас 80-90.
      Известно, что чем дольше работает Firefox и чем больше в нем открыто табов, тем сильнее он отжирает память и тормозит всю систему. Создатели говорят, что это фича, а не бага. Дескать, Firefox обильно кэширует отрендеренные страницы. А мы страдаем. Эту «фичу» можно частично нивелировать.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *