Reusing Message Objects

It is faster to reuse an existing message object than to destroy it and create a new one. Programs can gain efficiency by reusing message objects, whenever possible.

  • If a program repeatedly sends the exact same message content, then the best practice is to create that message object only once, sending it many times.
  • If a program sends many messages of the same format, with the same fields, but with varying field values, then the best practice is to reuse one message object, clearing and modifying individual field values appropriately before each send call.
  • If a program sends many messages of the same format, but the set of fields varies, then the best practice is to reuse one message object, clearing all of its fields and setting new values before each send call.

A program that sends a limited variety of messages can combine these tactics for reusing message objects. For each send call, it can select an appropriate message from a set of pre-constructed message objects, and modify as needed. To determine the optimum way to combine these tactics, test performance empirically.