mirror of
https://github.com/DaveGamble/cJSON.git
synced 2025-05-17 15:06:48 +08:00
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:
37
cJSON.c
37
cJSON.c
@ -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;
|
||||
|
Reference in New Issue
Block a user