Defer initialization of lists and dicts until an item is added.

Instead of pre-allocating every list with space for 10 items, don't
initialize it at all until the first Insert.

Instead of pre-allocating every dictionary with 17 buckets,
don't initialize it at all until the first Insert.
This commit is contained in:
Justin Azoff 2019-02-18 12:50:22 -05:00
parent aff3f4b3fd
commit 52dbaef6da
3 changed files with 37 additions and 31 deletions

View file

@ -6,33 +6,27 @@
#include "List.h"
#include "util.h"
static const int DEFAULT_CHUNK_SIZE = 10;
#define DEFAULT_LIST_SIZE 10
#define GROWTH_FACTOR 2
BaseList::BaseList(int size)
{
chunk_size = DEFAULT_CHUNK_SIZE;
num_entries = 0;
max_entries = 0;
entry = 0;
if ( size < 0 )
{
num_entries = max_entries = 0;
entry = 0;
}
else
{
if ( size > 0 )
chunk_size = size;
if ( size <= 0 )
return;
num_entries = 0;
entry = (ent *) safe_malloc(chunk_size * sizeof(ent));
max_entries = chunk_size;
}
max_entries = size;
entry = (ent *) safe_malloc(max_entries * sizeof(ent));
}
BaseList::BaseList(BaseList& b)
{
max_entries = b.max_entries;
chunk_size = b.chunk_size;
num_entries = b.num_entries;
if ( max_entries )
@ -58,7 +52,6 @@ void BaseList::operator=(BaseList& b)
free(entry);
max_entries = b.max_entries;
chunk_size = b.chunk_size;
num_entries = b.num_entries;
if ( max_entries )
@ -74,8 +67,7 @@ void BaseList::insert(ent a)
{
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size); // make more room
chunk_size *= 2;
resize(max_entries==0 ? DEFAULT_LIST_SIZE : max_entries*GROWTH_FACTOR); // make more room
}
for ( int i = num_entries; i > 0; --i )
@ -95,8 +87,7 @@ void BaseList::sortedinsert(ent a, list_cmp_func cmp_func)
// First append element.
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size);
chunk_size *= 2;
resize(max_entries==0 ? DEFAULT_LIST_SIZE : max_entries*GROWTH_FACTOR);
}
entry[num_entries++] = a;
@ -142,8 +133,7 @@ void BaseList::append(ent a)
{
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size); // make more room
chunk_size *= 2;
resize(max_entries==0 ? DEFAULT_LIST_SIZE : max_entries*GROWTH_FACTOR); // make more room
}
entry[num_entries++] = a;
@ -168,7 +158,6 @@ void BaseList::clear()
}
num_entries = max_entries = 0;
chunk_size = DEFAULT_CHUNK_SIZE;
}
ent BaseList::replace(int ent_index, ent new_ent)