From 4a546e7b2f471157c6f479df1ef687864fcbd89e Mon Sep 17 00:00:00 2001 From: Eric Haszlakiewicz Date: Sun, 24 May 2020 03:53:32 +0000 Subject: [PATCH] In arraylist, use malloc instead of calloc, avoid clearing with memeset until we really need to, and micro-optimize array_list_add(). --- arraylist.c | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/arraylist.c b/arraylist.c index e5524aca75..3e7bfa8950 100644 --- a/arraylist.c +++ b/arraylist.c @@ -40,13 +40,13 @@ struct array_list *array_list_new(array_list_free_fn *free_fn) { struct array_list *arr; - arr = (struct array_list *)calloc(1, sizeof(struct array_list)); + arr = (struct array_list *)malloc(sizeof(struct array_list)); if (!arr) return NULL; arr->size = ARRAY_LIST_DEFAULT_SIZE; arr->length = 0; arr->free_fn = free_fn; - if (!(arr->array = (void **)calloc(arr->size, sizeof(void *)))) + if (!(arr->array = (void **)malloc(arr->size * sizeof(void *)))) { free(arr); return NULL; @@ -92,11 +92,11 @@ static int array_list_expand_internal(struct array_list *arr, size_t max) if (!(t = realloc(arr->array, new_size * sizeof(void *)))) return -1; arr->array = (void **)t; - (void)memset(arr->array + arr->size, 0, (new_size - arr->size) * sizeof(void *)); arr->size = new_size; return 0; } +//static inline int _array_list_put_idx(struct array_list *arr, size_t idx, void *data) int array_list_put_idx(struct array_list *arr, size_t idx, void *data) { if (idx > SIZE_T_MAX - 1) @@ -106,6 +106,17 @@ int array_list_put_idx(struct array_list *arr, size_t idx, void *data) if (idx < arr->length && arr->array[idx]) arr->free_fn(arr->array[idx]); arr->array[idx] = data; + if (idx > arr->length) + { + /* Zero out the arraylist slots in between the old length + and the newly added entry so we know those entries are + empty. + e.g. when setting array[7] in an array that used to be + only 5 elements longs, array[5] and array[6] need to be + set to 0. + */ + memset(arr->array + arr->length, 0, (idx - arr->length) * sizeof(void *)); + } if (arr->length <= idx) arr->length = idx + 1; return 0; @@ -113,7 +124,17 @@ int array_list_put_idx(struct array_list *arr, size_t idx, void *data) int array_list_add(struct array_list *arr, void *data) { - return array_list_put_idx(arr, arr->length, data); + /* Repeat some of array_list_put_idx() so we can skip several + checks that we know are unnecessary when appending at the end + */ + size_t idx = arr->length; + if (idx > SIZE_T_MAX - 1) + return -1; + if (array_list_expand_internal(arr, idx + 1)) + return -1; + arr->array[idx] = data; + arr->length++; + return 0; } void array_list_sort(struct array_list *arr, int (*compar)(const void *, const void *))