Since I added a couple of functions program, it barely boots, starts the setup routine and directly goes out of memory.
I’ve been looking for the problem, and I realized that my memory oscillates during the execution of the program and precisely it is that, after boot, and with the setup routines, it reaches the least value, and probably results in my issue.
At this point, I’m starting to measure my posibillities. The first it’s to start lighten the code, but I don’t know if besides that I could do something more.
Could be possible to call the garbage collector in order to lighten the memory?
Any good trick or good-practice to lighten the code?
I will cover a few things you can do here but they are very generic. If you share some code with us I can give specifics.
Some some tried and true memory-reducing techniques:
- Never declare global variables using “local”. Use the “<-” syntax instead.
- Use const’s where possible as they are stored in left flash not imported to RAM.
- server.log() eats RAM (1kb per log entry?) until the log buffer is cleared. Don’t use them in hard loops.
- Each function definition takes up RAM, so don’t have create trivial functions and remove functions you don’t use.
- Watch out with classes, especially sub-classes. They chew RAM.
- Avoid deep nesting function calls including recursive functions as the stack fills up quickly.
- Don’t store lots of items in arrays. The array structure takes up more memory than the items themselves.
- Use blob’s instead of string’s where possible and appropriate. String’s are immutable so each time you want to add to a string, you are actually creating a new string.
I will add to this if I think of any more.
Remember this is embedded code. It needs to be tight. If you were using an Arduino, you would only have 2kb to work with. At least with the Imp you have nearly 100kb, but it still needs to be managed well.
…also, the next release has a lot more free memory (mainly due to squirrel taking a lot less space for almost all types of element - classes, etc). With a large program you may suddenly get 10-20kB more free memory.
Aron’s list is very comprehensive (I believe he in fact spends quite a lot of his time fitting lots of Squirrel into not much Imp). Some more details on some of his points are at http://devwiki.electricimp.com/doku.php?id=writingefficientsquirrel
Peter, you might want to add the missing ones to the docuwiki
@aron can I please PM you with some code for comment. Based on your points above I seem to be making almost every one of those mistakes.
Some pointers to be smallest/easiest changes to recover the most memory will be appreciated.