Mon, 20 Feb 2017 17:28:58 +0100
reduces amount of realloc calls in sstrsplit
ucx/string.c | file | annotate | diff | comparison | revisions |
1.1 --- a/ucx/string.c Mon Feb 20 17:12:14 2017 +0100 1.2 +++ b/ucx/string.c Mon Feb 20 17:28:58 2017 +0100 1.3 @@ -218,7 +218,8 @@ 1.4 } 1.5 1.6 ssize_t nmax = *n; 1.7 - sstr_t* result = (sstr_t*) almalloc(allocator, sizeof(sstr_t)); 1.8 + size_t arrlen = 16; 1.9 + sstr_t* result = (sstr_t*) almalloc(allocator, arrlen*sizeof(sstr_t)); 1.10 1.11 if (result) { 1.12 sstr_t curpos = s; 1.13 @@ -250,17 +251,20 @@ 1.14 1.15 /* allocate memory for the next string */ 1.16 j++; 1.17 - sstr_t* reallocated = (sstr_t*) 1.18 - alrealloc(allocator, result, j*sizeof(sstr_t)); 1.19 - if (reallocated) { 1.20 - result = reallocated; 1.21 - } else { 1.22 - for (ssize_t i = 0 ; i < j-1 ; i++) { 1.23 - alfree(allocator, result[i].ptr); 1.24 + if (j > arrlen) { 1.25 + arrlen *= 2; 1.26 + sstr_t* reallocated = (sstr_t*) alrealloc( 1.27 + allocator, result, arrlen*sizeof(sstr_t)); 1.28 + if (reallocated) { 1.29 + result = reallocated; 1.30 + } else { 1.31 + for (ssize_t i = 0 ; i < j-1 ; i++) { 1.32 + alfree(allocator, result[i].ptr); 1.33 + } 1.34 + alfree(allocator, result); 1.35 + *n = -2; 1.36 + return NULL; 1.37 } 1.38 - alfree(allocator, result); 1.39 - *n = -2; 1.40 - return NULL; 1.41 } 1.42 } else { 1.43 /* nmax reached, copy the _full_ remaining string */