Re: Massive memory optimization: flash functions! (+SPI SSD1
Posted: Tue Mar 17, 2015 11:37 pm
I can give a few pointers, but I don't have the free time to convert every one's module to flashMod for them... try it yourself and I'll help you with problems.
First, everything is global... you need to add local before most of your variables, or they will stick around in the global namespace forever, taking up space. The trick of memory optimization is usually NOT to avoid using memory, but to stop using it as soon as you are done with it.
Second, all those constants take up zero space in C, but they take up probably around 500 bytes in Lua. Why? INTEGRATIONTIME_700MS=0x00 is the same as _G["INTEGRATIONTIME_700MS"]=0.0 to Lua. That means the names of the variables themselves are key values in a table (which means they are represented as strings), and all numbers are 4 bytes (integers or floats, depending on your build). There's also some additional table overhead. The best approach from a memory standpoint is to use the numeric constants directly, and just add a comment of what it means. If the named constants are worth the memory usage, then go for it, but at least put them on your module's table rather than the global table.
Putting each of those functions on a module table and then running that table through flashMod() before returning it should make the heap after require much better. Again, try it and let me help you fix what doesn't work. Just remember to use colons instead of dots before functions, and use self instead of the module table to reference other functions or variables.
First, everything is global... you need to add local before most of your variables, or they will stick around in the global namespace forever, taking up space. The trick of memory optimization is usually NOT to avoid using memory, but to stop using it as soon as you are done with it.
Second, all those constants take up zero space in C, but they take up probably around 500 bytes in Lua. Why? INTEGRATIONTIME_700MS=0x00 is the same as _G["INTEGRATIONTIME_700MS"]=0.0 to Lua. That means the names of the variables themselves are key values in a table (which means they are represented as strings), and all numbers are 4 bytes (integers or floats, depending on your build). There's also some additional table overhead. The best approach from a memory standpoint is to use the numeric constants directly, and just add a comment of what it means. If the named constants are worth the memory usage, then go for it, but at least put them on your module's table rather than the global table.
Putting each of those functions on a module table and then running that table through flashMod() before returning it should make the heap after require much better. Again, try it and let me help you fix what doesn't work. Just remember to use colons instead of dots before functions, and use self instead of the module table to reference other functions or variables.