Page 1 of 1

Strings Module for Memory Optimization

Posted: Tue Jul 09, 2019 2:26 pm
by bruno963852
According to the official documentation, assigning a string to a variable instead of passing directly in a function is more efficient because the string will be saved in flash, example:
var = "My string is a good string"
print(var)

is better than:
print("My string is a good string")

at least it is what i understood.
So, knowing that, i'v been thinking if it is more memory efficient to save all the big strings you will be using in the project in a single module for reference, like a strings.py file, example:
strings.py file:
string1 = "this is string!
stirng2 = "this is another string"
string_to_print = "this string is the best string"

and in the main code:
import strings
print(string.string_to_print)

Am i crazy or it makes sense?

Re: Strings Module for Memory Optimization

Posted: Wed Jul 10, 2019 10:42 am
by jimmo
hi Bruno,

Unfortunately that's not quite what the documentation is saying. It's a bit subtle the way it's worded. There are two important clarifications:

- This only applies when freezing your module, and only when freezing as bytecode. i.e. this is not the case when your python file is just on the filesystem - you have to have compiled it into your firmware image. (You may be doing this, but you didn't mention that in your post). On pyboard you do this by putting your .py file into the ports/stm32/modules directory, it's similar on other ports -- there is more information in https://docs.micropython.org/en/latest/ ... ained.html.

- When freezing, it will apply automatically to all strings (and bytes(), ints, floats and complex). It doesn't need to be assigned to a variable.

That said - there's still a way in which using a "strings.py" could be a useful thing to do -- if you want all your regular code to be on the filesystem as regular Python files, then you can just bytecode-freeze strings.py. (I guess this makes sense if you don't plan to change strings.py as often as your code, probably true at least during development, and certainly useful if you just do it for your large strings).

Edit: If you are going to do it just for strings, then the process described in "Storing strings in flash" using qstr_info(1) is also a good alternative.

Let me know if you'd like some more information about how the compilation and RAM / flash works, especially in regard to the different ways of loading python code (.py on the filesystem, .mpy on the filesystem, frozen module in firmware, frozen bytecode in firmware).