adafruit / Adafruit_CircuitPython_APDS9960

Adafruit Bundle driver for APSD9960 Gesture breakout board
MIT License
10 stars 17 forks source link

Reducing memory footprint by using _naming for purely internal constants #37

Closed fivesixzero closed 2 years ago

fivesixzero commented 2 years ago

While preparing some potential fixes for review I realized that most prospective fixes will increase memory usage a bit.

After some discussions in the circuitpython-dev Discord channel with danh I tried applying leading-underscore naming to the slew of purely internal constants in the main driver file.

To see if this actually made a difference, I did some basic memory usage testing using a script I quickly put together. Its definitely not scientific - there are a bunch of other things that could be impacting memory usage - but at the very least it should provide some rough indication of whether this fix is worth the effort of submitting a PR. šŸ˜„

import board
import gc

i2c = board.I2C()

mem_pre_import, mem_post_import, mem_pre_instantiate, mem_post_instantiate = (0, 0, 0, 0)

gc.collect()
mem_pre_import = gc.mem_free()
from adafruit_apds9960.apds9960 import APDS9960
gc.collect()
mem_post_import = gc.mem_free()

gc.collect()
mem_pre_instantiate = gc.mem_free()
apds = APDS9960(i2c)
gc.collect()
mem_post_instantiate = gc.mem_free()
print("MEM Pre-import       | mem_free: {:7}".format(mem_pre_import))
print("MEM Post-import      | mem_free: {:7} | change: {:7}".format(mem_post_import, mem_post_import - mem_pre_import))
print("MEM Post-instantiate | mem_free: {:7} | change: {:7}".format(mem_post_instantiate, mem_post_instantiate - mem_pre_instantiate))

The table below shows the increase in memory usage from tests with four different versions of the library.

post-import post-instantiate mpy size
bundle 20211114 mpy 8,416 144 3,839
previous mpy 8,544 160 3,948
current mpy 8,464 144 3,794
constant_fix mpy (this PR) 7,856 144 3,364

The compiled file size dropped by more than 10%, which could be handy on some more limited boards. The memory usage savings weren't as strong but a 5% memory footprint reduction for just adding some underscores ain't bad.

fivesixzero commented 2 years ago

The commit in this PR has been included with #38 which is currently in draft status.

I'm leaving it open for now since its ready for merge and is a lot less work to review for merge than that the large refactor in the other PR.

fivesixzero commented 2 years ago

I also included the commit in this PR within #39, which has superseded #38.

Since that one is so big I'll leave this as a seprate PR in case some or all of the changes that PR don't work out.