Skip to content

Commit 2c77b64

Browse files
angeloINTJclaude
andcommitted
perf: replace std::sort with inline insertion sort (-1.5KB flash)
Custom sortStrings() in WebManager_History.cpp replaces two std::sort calls. Eliminates qsort (1,444B) from newlib link. Insertion sort is O(n^2) but n <= 365 (daily history files), worst case ~66K comparisons at 133MHz = ~2ms — negligible for HTTP request context. Flash: 98.1% -> 97.9% (saved 1,544 bytes) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 2222f33 commit 2c77b64

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

src/WebManager_History.cpp

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,18 @@
1717

1818
using ReadGuard = StorageManager::ReadGuard;
1919

20+
// Inline insertion sort (replaces std::sort, eliminates qsort ~1.4KB)
21+
static void sortStrings(String* arr, int n, bool descending) {
22+
for (int i = 1; i < n; i++) {
23+
String key = arr[i];
24+
int j = i - 1;
25+
while (j >= 0 && (descending ? arr[j] < key : key < arr[j])) {
26+
arr[j + 1] = arr[j]; j--;
27+
}
28+
arr[j + 1] = key;
29+
}
30+
}
31+
2032

2133
/* =========================================================================== */
2234
/* GET /api/history_multi?sensors=<csv>&range=<0..6>&end=<ep> */
@@ -121,7 +133,8 @@ void WebManager::handleApiHistoryMulti( ) {
121133
decimation = rangeDecimation[rangeIdx];
122134
cutoff = (rangeIdx == 6) ? 0 : (effectiveEnd - rangeDuration[rangeIdx]);
123135

124-
/* ── List of files to read ────────────────────────────────────────── */
136+
137+
/* ── List of files to read ────────────────────────────────────────── */
125138
std::vector<String> filesToRead;
126139
if (rangeIdx >= 4) {
127140
/* 1M, 1Y, MAX: list ALL files in directory (filter by epoch
@@ -133,7 +146,7 @@ void WebManager::handleApiHistoryMulti( ) {
133146
filesToRead.push_back(String(DIR_HISTORY) + "/" + dir.fileName( ));
134147
}
135148
}
136-
std::sort(filesToRead.begin( ), filesToRead.end( )); /* YYYYMMDD sorts chronologically */
149+
sortStrings(filesToRead.data( ), (int)filesToRead.size( ), false); /* YYYYMMDD ascending */
137150
} else {
138151
int daysToLoad = 1;
139152
switch (rangeIdx) {
@@ -1071,7 +1084,7 @@ void WebManager::handleApiHistoryDays( ) {
10711084
}
10721085
}
10731086

1074-
std::sort(files.begin( ), files.end( ), std::greater<String>( ));
1087+
sortStrings(files.data( ), (int)files.size( ), true); /* descending */
10751088

10761089
_server.setContentLength(CONTENT_LENGTH_UNKNOWN);
10771090
_server.send(200, "application/json", "");

0 commit comments

Comments
 (0)