strmap: take advantage of FLEXPTR_ALLOC_STR when relevant
By default, we do not use a mempool and strdup_strings is true; in this case, we can avoid both an extra allocation and an extra free by just over-allocating for the strmap_entry leaving enough space at the end to copy the key. FLEXPTR_ALLOC_STR exists for exactly this purpose, so make use of it. Also, adjust the case when we are using a memory pool and strdup_strings is true to just do one allocation from the memory pool instead of two so that the strmap_clear() and strmap_remove() code can just avoid freeing the key in all cases. Signed-off-by: Elijah Newren <newren@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Elijah Newren committed
Nov 11, 2020 at 20:02 UTC
23a276a9c4c8945aadbc323e12c970816eb43c27
2 files changed
+20
-16
strmap.c
+19
-16
@@ -59,11 +59,8 @@ static void strmap_free_entries_(struct strmap *map, int free_values)
59
hashmap_for_each_entry(&map->map, &iter, e, ent) {
60
if (free_values)
61
free(e->value);
62
- if (!map->pool) {
63
- if (map->strdup_strings)
64
- free((char*)e->key);
62
+ if (!map->pool)
63
free(e);
66
- }
64
}
65
}
66
@@ -84,16 +81,25 @@ static struct strmap_entry *create_entry(struct strmap *map,
81
void *data)
82
{
83
struct strmap_entry *entry;
87
- const char *key = str;
84
89
- entry = map->pool ? mem_pool_alloc(map->pool, sizeof(*entry))
90
- : xmalloc(sizeof(*entry));
85
+ if (map->strdup_strings) {
86
+ if (!map->pool) {
87
+ FLEXPTR_ALLOC_STR(entry, key, str);
88
+ } else {
89
+ size_t len = st_add(strlen(str), 1); /* include NUL */
90
+ entry = mem_pool_alloc(map->pool,
91
+ st_add(sizeof(*entry), len));
92
+ memcpy(entry + 1, str, len);
93
+ entry->key = (void *)(entry + 1);
94
+ }
95
+ } else if (!map->pool) {
96
+ entry = xmalloc(sizeof(*entry));
97
+ } else {
98
+ entry = mem_pool_alloc(map->pool, sizeof(*entry));
99
+ }
100
hashmap_entry_init(&entry->ent, strhash(str));
92
-
93
- if (map->strdup_strings)
94
- key = map->pool ? mem_pool_strdup(map->pool, str)
95
- : xstrdup(str);
96
- entry->key = key;
101
+ if (!map->strdup_strings)
102
+ entry->key = str;
103
entry->value = data;
104
return entry;
105
}
@@ -139,11 +145,8 @@ void strmap_remove(struct strmap *map, const char *str, int free_value)
145
return;
146
if (free_value)
147
free(ret->value);
142
- if (!map->pool) {
143
- if (map->strdup_strings)
144
- free((char*)ret->key);
148
+ if (!map->pool)
149
free(ret);
146
- }
150
}
151
152
void strintmap_incr(struct strintmap *map, const char *str, intptr_t amt)
strmap.h
+1
@@ -14,6 +14,7 @@ struct strmap_entry {
14
struct hashmap_entry ent;
15
const char *key;
16
void *value;
17
+ /* strmap_entry may be allocated extra space to store the key at end */
18
};
19
20
int cmp_strmap_entry(const void *hashmap_cmp_fn_data,