Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use sync.Pool to reduce the number of memory allocations on encode #126

Open
atlas-comstock opened this issue Jan 13, 2023 · 1 comment
Open
Assignees

Comments

@atlas-comstock
Copy link
Collaborator

In this encoding part, we have too many allocations:

e.batch = &pb.Batch{Events: make([]*pb.Event, 0, len(events))}

We can optimise it like this(Just an example)

type encoder struct {
    // ... other fields ...
    batchPool *sync.Pool
}

func newEncoder() *encoder {
    e := new(encoder)
    e.batchPool = &sync.Pool{
        New: func() interface{} {
            return &pb.Batch{Events: make([]*pb.Event, 0, batchSize)}
        },
    }
    return e
}

// Encode implements formatter interface
func (e *encoder) Encode(events []Event) *pb.Batch {
    e.Lock()
    defer e.Unlock()

    e.next = 0
    e.dictionary = make(map[string]uint32, len(events))
    e.batch = e.batchPool.Get().(*pb.Batch)
    e.batch.Events = e.batch.Events[:0]

    // Write the events
    for _, ev := range events {
        encoded := e.encodeEvent(ev)
        e.batch.Events = append(e.batch.Events, encoded)
    }

    // Write the interned strings
    e.writeDictionary()
    e.batchPool.Put(e.batch)
    return e.batch
}
@kelindar
Copy link
Collaborator

You should only release the data once it's no longer used, otherwise you'll end up with corrupt memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants