Go to the previous, next section.

Extra Fast Growing Objects

The usual functions for growing objects incur overhead for checking whether there is room for the new growth in the current chunk. If you are frequently constructing objects in small steps of growth, this overhead can be significant.

You can reduce the overhead by using special "fast growth" functions that grow the object without checking. In order to have a robust program, you must do the checking yourself. If you do this checking in the simplest way each time you are about to add data to the object, you have not saved anything, because that is what the ordinary growth functions do. But if you can arrange to check less often, or check more efficiently, then you make the program faster.

The function obstack_room returns the amount of room available in the current chunk. It is declared as follows:

Function: size_t obstack_room (struct obstack *obstack_ptr)

This returns the number of bytes that can be added safely to the current growing object (or to an object about to be started) in obstack obstack using the fast growth functions.

While you know there is room, you can use these fast growth functions for adding data to a growing object:

Function: void obstack_1grow_fast (struct obstack *obstack_ptr, char c)

The function obstack_1grow_fast adds one byte containing the character c to the growing object in obstack obstack_ptr.

Function: void obstack_blank_fast (struct obstack *obstack_ptr, size_t size)

The function obstack_blank_fast adds size bytes to the growing object in obstack obstack_ptr without initializing them.

When you check for space using obstack_room and there is not enough room for what you want to add, the fast growth functions are not safe. In this case, simply use the corresponding ordinary growth function instead. Very soon this will copy the object to a new chunk; then there will be lots of room available again.

So, each time you use an ordinary growth function, check afterward for sufficient space using obstack_room. Once the object is copied to a new chunk, there will be plenty of space again, so the program will start using the fast growth functions again.

Here is an example:

add_string (struct obstack *obstack, char *ptr, size_t len)
  while (len > 0)
      if (obstack_room (obstack) > len)
          /* We have enough room: add everything fast.  */
          while (len-- > 0)
            obstack_1grow_fast (obstack, *ptr++);
          /* Not enough room. Add one character slowly,
             which may copy to a new chunk and make room.  */
          obstack_1grow (obstack, *ptr++);

Go to the previous, next section.