Reduce NVS writes to Flash

Gilbert
Posts: 41
Joined: Wed Sep 16, 2020 2:58 pm

Reduce NVS writes to Flash

Postby Gilbert » Sun Jan 17, 2021 10:10 am

Hi,
I'm saving important data to flash using the Preferences library, mainly because prefs is more convenient to use than the nvs library.
One thing that strikes me is that preferences issues a "commit" with every "put"-call I make. Now here's the issue: I'm assuming that nvs rewrites an entire sector whenever a commit is executed. Hence my thought is that when I save 10 variables, the sector will be written 10 times - even when all my variables are physically located in the same sector, because of the "commit" which goes with every "put". Now let's assume that I collect my 10 variables in a single struct and I only save the entire struct with a single call to putBytes, that will result in a single write to flash i.s.o. 10 separate writes. If I'm right, that should extend the "lifetime" of my flash in terms of write cycles by a factor of 10?
Of course I could make calls to nvs functions directly, i.s.o. using preferences, but in essence the challenge remains the same: reduce the number of commits as much as possible. And that also means, limit the number of different namespaces, since commit is tied to a namespace and has to be issued for every namespace separately. Am I right or am I missing something?

ESP_Sprite
Posts: 9730
Joined: Thu Nov 26, 2015 4:08 am

Re: Reduce NVS writes to Flash

Postby ESP_Sprite » Sun Jan 17, 2021 2:04 pm

You are not entirely wrong in that a commit indeed writes to flash, but you need to keep in mind it's the erase cycles that kill flash, not the write cycles. Nvs will erase only when it absolutely needs to (as in: it can't append your data to an existing, partially empty sector) so writing your data separately or all at the same time doesn't have that much influence. (It will help a little bit because of reduced overhead, but that may be offset by the fact that you need to rewrite everything when one little thing changes.)

In general, rule of thumb wrt NVS longevity is: as long as you don't rewrite your data ridiculously often (as in: once per second, for years on end), you don't have to worry about it.

Gilbert
Posts: 41
Joined: Wed Sep 16, 2020 2:58 pm

Re: Reduce NVS writes to Flash

Postby Gilbert » Sun Jan 17, 2021 4:51 pm

Sounds good. Thanks for that.
Using my original assumptions (10 variables saved 10 times a day every day of the week) I arrived at a little over 3 years before the limit (which I assumed to 100k write cycles) would be reached. That's a bit too short for my liking. Hence I wanted to explore my options. Since the amount of data to be saved that frequently is fairly small (somewhere in the order of 10..20 bytes), I shouldn't worry about it.

Who is online

Users browsing this forum: No registered users and 25 guests