object_array_remove_duplicates(): rewrite to reduce copying
The old version copied one entry to its destination position, then deleted any matching entries from the tail of the array. This required the tail of the array to be copied multiple times. It didn't affect the complexity of the algorithm because the whole tail has to be searched through anyway. But all the copying was unnecessary. Instead, check for the existence of an entry with the same name in the *head* of the list before copying an entry to its final position. This way each entry has to be copied at most one time. Extract a helper function contains_name() to do a bit of the work. Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Michael Haggerty committed
May 25, 2013 at 11:08 UTC
1506510c170d23b8f769757dc81904f334c40281
2 files changed
+26
-12
object.c
+21
-11
@@ -294,22 +294,32 @@ void object_array_filter(struct object_array *array,
294
array->nr = dst;
295
}
296
297
+/*
298
+ * Return true iff array already contains an entry with name.
299
+ */
300
+static int contains_name(struct object_array *array, const char *name)
301
+{
302
+ unsigned nr = array->nr, i;
303
+ struct object_array_entry *object = array->objects;
304
+
305
+ for (i = 0; i < nr; i++, object++)
306
+ if (!strcmp(object->name, name))
307
+ return 1;
308
+ return 0;
309
+}
310
+
311
void object_array_remove_duplicates(struct object_array *array)
312
{
299
- unsigned int ref, src, dst;
313
+ unsigned nr = array->nr, src;
314
struct object_array_entry *objects = array->objects;
315
302
- for (ref = 0; ref + 1 < array->nr; ref++) {
303
- for (src = ref + 1, dst = src;
304
- src < array->nr;
305
- src++) {
306
- if (!strcmp(objects[ref].name, objects[src].name))
307
- continue;
308
- if (src != dst)
309
- objects[dst] = objects[src];
310
- dst++;
316
+ array->nr = 0;
317
+ for (src = 0; src < nr; src++) {
318
+ if (!contains_name(array, objects[src].name)) {
319
+ if (src != array->nr)
320
+ objects[array->nr] = objects[src];
321
+ array->nr++;
322
}
312
- array->nr = dst;
323
}
324
}
325
object.h
+5
-1
@@ -96,7 +96,11 @@ typedef int (*object_array_each_func_t)(struct object_array_entry *, void *);
96
void object_array_filter(struct object_array *array,
97
object_array_each_func_t want, void *cb_data);
98
99
-void object_array_remove_duplicates(struct object_array *);
99
+/*
100
+ * Remove from array all but the first entry with a given name.
101
+ * Warning: this function uses an O(N^2) algorithm.
102
+ */
103
+void object_array_remove_duplicates(struct object_array *array);
104
105
void clear_object_flags(unsigned flags);
106