Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

perf comm str: Avoid sort during insert

The array is sorted, so just move the elements and insert in order.

Fixes: 13ca628716c6 ("perf comm: Add reference count checking to 'struct comm_str'")
Reported-by: Matt Fleming <matt@readmodwrite.com>
Signed-off-by: Ian Rogers <irogers@google.com>
Tested-by: Matt Fleming <matt@readmodwrite.com>
Cc: Steinar Gunderson <sesse@google.com>
Cc: Athira Rajeev <atrajeev@linux.vnet.ibm.com>
Link: https://lore.kernel.org/r/20240703172117.810918-2-irogers@google.com
Signed-off-by: Namhyung Kim <namhyung@kernel.org>

authored by

Ian Rogers and committed by
Namhyung Kim
feaaa8be 2eae307e

+18 -11
+18 -11
tools/perf/util/comm.c
··· 86 86 return result; 87 87 } 88 88 89 - static int comm_str__cmp(const void *_lhs, const void *_rhs) 90 - { 91 - const struct comm_str *lhs = *(const struct comm_str * const *)_lhs; 92 - const struct comm_str *rhs = *(const struct comm_str * const *)_rhs; 93 - 94 - return strcmp(comm_str__str(lhs), comm_str__str(rhs)); 95 - } 96 - 97 89 static int comm_str__search(const void *_key, const void *_member) 98 90 { 99 91 const char *key = _key; ··· 161 169 } 162 170 result = comm_str__new(str); 163 171 if (result) { 164 - comm_strs->strs[comm_strs->num_strs++] = result; 165 - qsort(comm_strs->strs, comm_strs->num_strs, sizeof(struct comm_str *), 166 - comm_str__cmp); 172 + int low = 0, high = comm_strs->num_strs - 1; 173 + int insert = comm_strs->num_strs; /* Default to inserting at the end. */ 174 + 175 + while (low <= high) { 176 + int mid = low + (high - low) / 2; 177 + int cmp = strcmp(comm_str__str(comm_strs->strs[mid]), str); 178 + 179 + if (cmp < 0) { 180 + low = mid + 1; 181 + } else { 182 + high = mid - 1; 183 + insert = mid; 184 + } 185 + } 186 + memmove(&comm_strs->strs[insert + 1], &comm_strs->strs[insert], 187 + (comm_strs->num_strs - insert) * sizeof(struct comm_str *)); 188 + comm_strs->num_strs++; 189 + comm_strs->strs[insert] = result; 167 190 } 168 191 } 169 192 up_write(&comm_strs->lock);