Improve performance of adding item to array (#448)

* use prev pointer when adding item to array

Co-authored-by: xiaomianhehe <hongshaokai@hotmail.com>
Co-authored-by: Alanscut <scut@163.com>

Date:   Tue Feb 18 11:54:23 2020 +0800

* add testcase for cJSON_DeleteItemFromArray
This commit is contained in:
Alan Wang
2020-03-24 16:17:25 +08:00
committed by GitHub
parent fa28d82f2e
commit 3ece4c893c
2 changed files with 67 additions and 13 deletions

37
cJSON.c
View File

@ -1871,20 +1871,33 @@ static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
}
child = array->child;
/*
* To find the last item in array quickly, we use prev in array
*/
if (child == NULL)
{
/* list is empty, start new one */
array->child = item;
item->prev = item;
item->next = NULL;
}
else
{
/* append to the end */
while (child->next)
if (child->prev)
{
child = child->next;
suffix_object(child->prev, item);
array->child->prev = item;
}
else
{
while (child->next)
{
child = child->next;
}
suffix_object(child, item);
array->child->prev = item;
}
suffix_object(child, item);
}
return true;
@ -2095,7 +2108,7 @@ CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const it
return NULL;
}
if (item->prev != NULL)
if (item != parent->child)
{
/* not the first element */
item->prev->next = item->next;
@ -2206,14 +2219,20 @@ CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON
{
replacement->next->prev = replacement;
}
if (replacement->prev != NULL)
{
replacement->prev->next = replacement;
}
if (parent->child == item)
{
parent->child = replacement;
}
else
{ /*
* To find the last item in array quickly, we use prev in array.
* We can't modify the last item's next pointer where this item was the parent's child
*/
if (replacement->prev != NULL)
{
replacement->prev->next = replacement;
}
}
item->next = NULL;
item->prev = NULL;