Skip to content

Commit

Permalink
Speed up bitwriter_grow_ by growing exponentially
Browse files Browse the repository at this point in the history
Growing up to the max allowed size took roughly 4000 reallocations,
which can be expensive. Now grow exponentially, which requires
about 30 reallocations up to max size.
  • Loading branch information
ktmf01 committed Dec 4, 2024
1 parent 070622c commit d1d72aa
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/libFLAC/bitwriter.c
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ typedef FLAC__uint64 FLAC__bwtemp;
* next one.
*/
static const uint32_t FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
/* When growing, increment 4K at a time */
static const uint32_t FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
/* When growing, increment with 1/4th at a time */
static const uint32_t FLAC__BITWRITER_DEFAULT_GROW_FRACTION = 2; /* means grow by >> 2 (1/4th) of current size */

#define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
#define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
Expand Down Expand Up @@ -131,11 +131,11 @@ FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, uint32_t bits_to_add)
* To prevent chrashing, give up */
return false;

/* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
/* As reallocation can be quite expensive, grow exponentially */
if((new_capacity - bw->capacity) < (bw->capacity >> FLAC__BITWRITER_DEFAULT_GROW_FRACTION))
new_capacity = bw->capacity + (bw->capacity >> FLAC__BITWRITER_DEFAULT_GROW_FRACTION);

/* make sure we got everything right */
FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
FLAC__ASSERT(new_capacity > bw->capacity);
FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));

Expand Down

0 comments on commit d1d72aa

Please sign in to comment.