Strings Module for Memory Optimization

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Posts: 2
Joined: Thu May 30, 2019 3:21 pm

Strings Module for Memory Optimization

Post by bruno963852 » Tue Jul 09, 2019 2:26 pm

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"

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 file, example: 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

Am i crazy or it makes sense?

User avatar
Posts: 328
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: Strings Module for Memory Optimization

Post by jimmo » Wed Jul 10, 2019 10:42 am

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 ... 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 "" 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 (I guess this makes sense if you don't plan to change 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).

Post Reply