diff --git a/printbuf.c b/printbuf.c index 9d6cc14..1fef3b0 100644 --- a/printbuf.c +++ b/printbuf.c @@ -28,15 +28,21 @@ #include "debug.h" #include "printbuf.h" +static int printbuf_initial_size = 32; static int printbuf_extend(struct printbuf *p, int min_size); +void json_global_set_printbuf_initial_size(int size) +{ + printbuf_initial_size = size; +} + struct printbuf* printbuf_new(void) { struct printbuf *p; p = (struct printbuf*)calloc(1, sizeof(struct printbuf)); if(!p) return NULL; - p->size = 32; + p->size = printbuf_initial_size; p->bpos = 0; if(!(p->buf = (char*)malloc(p->size))) { free(p); diff --git a/printbuf.h b/printbuf.h index 3985537..7bd94be 100644 --- a/printbuf.h +++ b/printbuf.h @@ -81,6 +81,27 @@ printbuf_reset(struct printbuf *p); extern void printbuf_free(struct printbuf *p); +/** + * Set initial size allocation for memory when creating strings, + * as is done for example in json_object_to_json_string(). The + * default size is 32, which is very conservative. If an app + * knows it typically deals with larger strings, performance + * can be improved by setting the initial size to a different + * number, e.g. 1k. Note that this also means that memory + * consumption can increase. How far entriely depens on the + * application and its use of json-c. + * + * Note: each time this function is called, the initial size is + * changed to the given value. Already existing elements are not + * affected. This function is usually meant to be called just once + * at start of an application, but there is no harm calling it more + * than once. Note that the function is NOT thread-safe and must not + * be called on different threads concurrently. + * + * @param size new initial size for printbuf (formatting buffer) + */ +extern void +json_global_set_printbuf_initial_size(int size); #ifdef __cplusplus } #endif