From f3e6908bf69cc3dd9bfc0f1a3e909c297c3b2996 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 2 Feb 2026 19:23:33 +0000 Subject: [PATCH] perf(bar): Optimize drawstatusbar with stack allocation Replaced heap allocation (malloc/free) with stack allocation for status text processing in `drawstatusbar`. This function is a hot path called on every status update (e.g., clock tick). - Introduced a 1024-byte stack buffer (matching `stext` global size). - Fallback to malloc only if text exceeds buffer size. - Reduces allocator churn and improves efficiency. Verification: - `make clean && make` passes. - Verified manual logic for buffer usage and cleanup. Co-authored-by: paperbenni <15818888+paperbenni@users.noreply.github.com> --- .jules/bolt.md | 3 +++ bar.c | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 .jules/bolt.md diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 00000000..b4fe5fa7 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2026-02-02 - Heap Allocation in Hot Path (drawstatusbar) +**Learning:** The `drawstatusbar` function allocates memory via `malloc` on every call to process the status text. Since the status text is typically small (capped at 1024 bytes by `stext`) and updated frequently (e.g., every second), this creates unnecessary heap churn. +**Action:** Use a stack buffer (Small String Optimization) for typical sizes and fallback to heap only when necessary. This reduces allocator overhead in the rendering loop. diff --git a/bar.c b/bar.c index 8476144a..5c63a8df 100644 --- a/bar.c +++ b/bar.c @@ -55,12 +55,15 @@ int drawstatusbar(Monitor *m, int bh, char *stext) { short isCode = 0; char *text; char *p; + char buf[1024]; len = strlen(stext) + 1; - if (!(text = (char *)malloc(sizeof(char) * len))) { + if (len < sizeof(buf)) { + p = buf; + } else if (!(p = (char *)malloc(sizeof(char) * len))) { die("malloc"); } - p = text; + text = p; memcpy(text, stext, len); /* compute width of the status text */ @@ -194,7 +197,9 @@ int drawstatusbar(Monitor *m, int bh, char *stext) { } drw_setscheme(drw, statusscheme); - free(p); + if (p != buf) { + free(p); + } return ret; }