Optimize search result finalization by reallocating in place
Replace the malloc/copy/free sequence with a single realloc that shrinks temp_results to its exact size and returns it directly. This * eliminates an extra allocation and memory copy * simplifies cleanup logic * retains correct failure handling (temp_results unchanged on realloc failure) Also drop the superfluous trailing space at EOF and add package-lock.json to version control to lock Node.js dependencies.
This commit is contained in:
@@ -307,24 +307,17 @@ SearchResult* search_index(SearchIndex* index, const char* query, float cutoff,
|
|||||||
// Sort results by similarity
|
// Sort results by similarity
|
||||||
qsort(temp_results, *num_results, sizeof(SearchResult), compare_results);
|
qsort(temp_results, *num_results, sizeof(SearchResult), compare_results);
|
||||||
|
|
||||||
// Allocate final result array with exact size
|
// Shrink temp_results to exact size and return it directly
|
||||||
SearchResult* results = (SearchResult*)malloc(*num_results * sizeof(SearchResult));
|
SearchResult* results = (SearchResult*)realloc(
|
||||||
|
temp_results, *num_results * sizeof(SearchResult));
|
||||||
if (!results) {
|
if (!results) {
|
||||||
// Free all strings in temp_results
|
// realloc failure – temp_results unchanged, clean up
|
||||||
for (int i = 0; i < *num_results; i++) {
|
for (int i = 0; i < *num_results; i++) {
|
||||||
free(temp_results[i].string);
|
free(temp_results[i].string);
|
||||||
}
|
}
|
||||||
free(temp_results);
|
free(temp_results);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy results to final array
|
|
||||||
for (int i = 0; i < *num_results; i++) {
|
|
||||||
results[i].string = temp_results[i].string;
|
|
||||||
results[i].similarity = temp_results[i].similarity;
|
|
||||||
}
|
|
||||||
free(temp_results);
|
|
||||||
|
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user