Create and Delete DDS entities outside of the write() or read() loop

Unlike when creating a socket and sending a UDP packet, creating DDS entities is more heavyweight. For example, various data structures are being allocated, multiple threads are created, transports are initialized, sockets or shared memory segments are created and the discovery automatically starts when the DDS entities are enabled.

In addition to this, data will not be sent from DataWriters to DataReaders if they have not discovered each other.  The discovery process takes more time than calling write() or read(), so it is almost guaranteed that if you create a DataWriter or DataReader within a write() or read() loop, you are going to lose data.

Thus it is recommended to manage the creation and deletion of DDS entities outside of the  write() and read() loop.  Typically, you will create them up front when you initialize your application, but this will depend on your application design.

(Note: for more information on techniques for not losing initial data during discovery, see this knowledge base article).