diff --git a/broker.go b/broker.go index afdf05d..43af097 100644 --- a/broker.go +++ b/broker.go @@ -66,8 +66,8 @@ type broker struct { topics topics // topic subscriptions } -func newBroker() *broker { - return &broker{make(topics)} +func newBroker(size int) *broker { + return &broker{make(topics, size)} } // Register associate subscriber to broker topics. diff --git a/broker_test.go b/broker_test.go index 815ed2a..bf0b452 100644 --- a/broker_test.go +++ b/broker_test.go @@ -7,7 +7,7 @@ import ( ) func TestRegister(t *testing.T) { - event := newBroker() + event := newBroker(4) subscriber := newSubscriber() event.Register(NewPeerDetected, subscriber) event.Register(PeerDisconnected, subscriber) @@ -47,7 +47,7 @@ func TestRegister(t *testing.T) { } func TestUnregister(t *testing.T) { - broker := newBroker() + broker := newBroker(4) subscriber := newSubscriber() broker.Register(MessageReceived, subscriber) broker.Register(NewPeerDetected, subscriber) @@ -61,7 +61,7 @@ func TestUnregister(t *testing.T) { } func TestUnregisterExpectedLen(t *testing.T) { - broker := newBroker() + broker := newBroker(4) subscriber := newSubscriber() broker.Register(MessageReceived, subscriber) broker.Register(NewPeerDetected, subscriber) @@ -75,7 +75,7 @@ func TestUnregisterExpectedLen(t *testing.T) { } func TestInvalidUnregister(t *testing.T) { - broker := newBroker() + broker := newBroker(4) subscriber := newSubscriber() // Remove self listening from broker events success := broker.Unregister(MessageReceived, subscriber) @@ -172,7 +172,7 @@ func TestTopicRemoveInvalid(t *testing.T) { func TestPublish(t *testing.T) { var result Signal subscriber := newSubscriber() - broker := newBroker() + broker := newBroker(4) session := mockSession(&mockConn{}, PeerAPb) header1 := header{newPeer(session), NewPeerDetected} @@ -212,7 +212,7 @@ func TestPublish(t *testing.T) { } func TestInvalidPublish(t *testing.T) { - broker := newBroker() + broker := newBroker(4) session := mockSession(&mockConn{}, PeerAPb) header1 := header{newPeer(session), NewPeerDetected} signaling := Signal{header1, ""} diff --git a/events.go b/events.go index ac5d643..0b2d15f 100644 --- a/events.go +++ b/events.go @@ -35,7 +35,10 @@ type events struct { func newEvents() *events { subscriber := newSubscriber() - broker := newBroker() + // !IMPORTANT if new events are added the size should be equal to new events number. + // we need only 4 spaces one for each event, adding this avoids potential map growth. + // https://100go.co/#inefficient-map-initialization-27 + broker := newBroker(4) // register default events broker.Register(NewPeerDetected, subscriber) broker.Register(MessageReceived, subscriber)