Minimize allocations for frame tvbuffs and Buffers.

Try to minimize the number of times we allocate memory for Buffers and
Buffer data.

Change-Id: I738fdc64e571772ef4ba6335d49087277dd7b430
Reviewed-on: https://code.wireshark.org/review/16577
Reviewed-by: Gerald Combs <gerald@wireshark.org>
Petri-Dish: Gerald Combs <gerald@wireshark.org>
Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org>
Reviewed-by: Anders Broman <a.broman58@gmail.com>
This commit is contained in:
Gerald Combs 2016-07-21 17:34:56 -07:00 committed by Anders Broman
parent e3a15cfbb2
commit b2e4a7e21c
2 changed files with 32 additions and 7 deletions

View File

@ -69,6 +69,8 @@ frame_read(struct tvb_frame *frame_tvb, struct wtap_pkthdr *phdr, Buffer *buf)
return TRUE;
}
static GPtrArray *buffer_cache = NULL;
static void
frame_cache(struct tvb_frame *frame_tvb)
{
@ -77,9 +79,14 @@ frame_cache(struct tvb_frame *frame_tvb)
wtap_phdr_init(&phdr);
if (frame_tvb->buf == NULL) {
frame_tvb->buf = (struct Buffer *) g_malloc(sizeof(struct Buffer));
if G_UNLIKELY(!buffer_cache) buffer_cache = g_ptr_array_sized_new(1024);
if (buffer_cache->len > 0) {
frame_tvb->buf = (struct Buffer *) g_ptr_array_remove_index(buffer_cache, buffer_cache->len - 1);
} else {
frame_tvb->buf = (struct Buffer *) g_malloc(sizeof(struct Buffer));
}
/* XXX, register frame_tvb to some list which frees from time to time not used buffers :] */
ws_buffer_init(frame_tvb->buf, frame_tvb->tvb.length + frame_tvb->offset);
if (!frame_read(frame_tvb, &phdr, frame_tvb->buf))
@ -98,8 +105,7 @@ frame_free(tvbuff_t *tvb)
if (frame_tvb->buf) {
ws_buffer_free(frame_tvb->buf);
g_free(frame_tvb->buf);
g_ptr_array_add(buffer_cache, frame_tvb->buf);
}
}

View File

@ -25,12 +25,27 @@
#include "buffer.h"
#define SMALL_BUFFER_SIZE (2 * 1024) /* Everyone still uses 1500 byte frames, right? */
static GPtrArray *small_buffers = NULL; /* Guaranteed to be at least SMALL_BUFFER_SIZE */
/* XXX - Add medium and large buffers? */
/* Initializes a buffer with a certain amount of allocated space */
void
ws_buffer_init(Buffer* buffer, gsize space)
{
buffer->data = (guint8*)g_malloc(space);
buffer->allocated = space;
if G_UNLIKELY(!small_buffers) small_buffers = g_ptr_array_sized_new(1024);
if (space <= SMALL_BUFFER_SIZE) {
if (small_buffers->len > 0) {
buffer->data = (guint8*) g_ptr_array_remove_index(small_buffers, small_buffers->len - 1);
} else {
buffer->data = (guint8*)g_malloc(SMALL_BUFFER_SIZE);
}
buffer->allocated = SMALL_BUFFER_SIZE;
} else {
buffer->data = (guint8*)g_malloc(space);
buffer->allocated = space;
}
buffer->start = 0;
buffer->first_free = 0;
}
@ -39,7 +54,11 @@ ws_buffer_init(Buffer* buffer, gsize space)
void
ws_buffer_free(Buffer* buffer)
{
g_free(buffer->data);
if (buffer->allocated == SMALL_BUFFER_SIZE) {
g_ptr_array_add(small_buffers, buffer->data);
} else {
g_free(buffer->data);
}
buffer->data = NULL;
}