nicegui: Server side memory leak when clearing ui.code()
First Check
- I added a very descriptive title here.
- This is not a Q&A. I am sure something is wrong with NiceGUI or its documentation.
- I used the GitHub search to find a similar issue and came up empty.
Example Code
from nicegui import ui
row = ui.row()
i = 0
def more_code():
global i
row.clear()
with row:
for k in range(50):
ui.code(language='xml', content=f'<data>{i}</data>')
i += 1
ui.timer(callback=more_code, interval=1)
ui.run()
Description
I noticed that when I create, clear and re-create a bunch of ui.code() elements, memory usage on the server creeps up. The given example creeps by 1 MB every 1-3 seconds. A real life example reached 4 gigs before becoming so slow that it had to be restarted. Tested in real life on Linux and the minimal example tested on Windows.
NiceGUI Version
2.20.0
Python Version
Python 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 15:28:43) [MSC v.1943 64 bit (ARM64)] on win32
Browser
Chrome
Operating System
Windows
Additional Context
No response
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 23 (13 by maintainers)
Commits related to this issue
- Use code.js component to avoid memory-leaky on_connect registration (#4919) ### Motivation The `ui.on_connect` registration of a lambda function in the initializer of `ui.code` causes a memory leak ... — committed to zauberzeug/nicegui by falkoschindler a year ago
- fix memory leak due to timer not being nested inside `ui.code` element (fixes #4912) — committed to bhardwajRahul/nicegui by falkoschindler a year ago
- Let `ui.header` update `scrollPaddingTop` more nicely with a custom header.js component (#4937) ### Motivation In https://github.com/zauberzeug/nicegui/issues/4912#issuecomment-3035026068 we noticed... — committed to zauberzeug/nicegui by falkoschindler a year ago
You guys are really fast and professional! Thanks for a great product 😀
Some insights:
ui.codeseems to be caused bytimer(0.1, self._update_copy_button).The leak forNo, I didn’t delete elements fromui.headerandui.left_drawer/ui.right_drawerseems to be caused by the linewith context.client.layout:.client.layoutbut only fromclient.content.ui.headerI noticedadd_body_htmlbeing called again and again which we should avoid.My test script:
Notable things:
ui.codeinstances)tracemallocindicates:self.client.on_connectinui.codewill append toClient.connect_handlers. That list gets longer and longer, and so the memory is leaked from there (investigating axing that and see if memory still grows to the same degree)@evnchn: It’s
ui.code!!! (Notui.code_mirror.) 😉