• Why would that be? Let's say we want to write a whole page and set every byte to its relative address. The bulk write solution would allocate an array buffer of 256 bytes, iterate over the buffer in a loop to set the data and then call the bulk write function. That function would iterate over the buffer again and write it to SPI. By contrast, with fine-grain functions, you would not even allocate a buffer and have only one loop which writes directly to SPI. I don't see why this should be slower? The user can even directly call spi.send and only use the module to initiate and finish the write operation.

    By the way, an improvement I can think of would be to replace this code:

    Flash.prototype.send = function(data) {
      // sends data and returns result
      return this.spi.send(data);
    };
    

    by this code in the constructor:

    function Flash(spi, csPin) {
      this.write = this.spi.send;
      ...
    

    Treating a whole sector as a page is an expensive workaround, because it reduces the number of pages by factor 16. After all, once you have erased a sector, you have 16 empty pages and you don't have to write them all at once. You can even write single bytes to anywhere you like. The only thing you cannot do is overwrite data in a location that was not previously erased (but "previously" does not have to mean "just before the write"). Thus, treating a whole sector as a page creates many limitations. A nicer approach would be smarter code which - when data within a page needs to be overwritten - copies the page to a free page. When free pages become scarce, it could relocate pages to free up sectors and erase them. But that functionality would essentially be a file system. It would be possible to implement such a file system and abstract all the complexity away from the user so that the flash behaves like a RAM... but then it would be very inefficient, so I assume that for typical Espruino applications the user should keep in mind it's a flash and deal with that complexity. If that's not an option, they should be using a non-volatile RAM instead.

About

Avatar for Dennis @Dennis started