summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEric Haszlakiewicz <erh+git@nimenees.com>2020-05-24 03:53:32 +0000
committerEric Haszlakiewicz <erh+git@nimenees.com>2020-05-24 03:54:04 +0000
commit4a546e7b2f471157c6f479df1ef687864fcbd89e (patch)
tree25d583ef795d37492ccb00f1086914fbf6ec6cf8
parentfbe15436447b8b6e2c9eb4419fdc37cc8ef5b2cc (diff)
downloadjson-c-4a546e7b2f471157c6f479df1ef687864fcbd89e.tar.gz
In arraylist, use malloc instead of calloc, avoid clearing with memeset until we really need to, and micro-optimize array_list_add().
-rw-r--r--arraylist.c29
1 files changed, 25 insertions, 4 deletions
diff --git a/arraylist.c b/arraylist.c
index e5524ac..3e7bfa8 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 *))