Reuse of Java Encoding Objects

The simple example above showed the procedure to encode a single record. But what if you had to encode a series of the same type of record over and over again?

In such cases, you can avoid some object creation and garbage collection by reusing objects you have already created. The generated classes and the ASN1C runtime classes can often be viewed as reusable containers into which you can simply assign new data.

To show an example of object reuse, suppose we were going to encode a series of octet strings. The ASN.1 type for our data might be:

   Data ::= SEQUENCE {
      first OCTET STRING,
      second OCTET STRING,
      third OCTET STRING
   }

The generated Java class would contain public member variables for each of the octet strings:

   public Asn1OctetString first;
   public Asn1OctetString second;
   public Asn1OctetString third;

The most efficient way to repopulate these variables within a loop would be simply to assign the data to be encoded to the public value field of the Asn1OctetString objects. You do not need to create new Asn1OctetString or Data objects each time.

A code snippet showing how this could be done is as follows:

   // Step 1: Create Data and Asn1JsonOutputStream objects for use in
   // the loop..

   Data data = new Data(null, null, null); // creates empty octet string objects
   Asn1JsonOutputStream encodeStream = new Asn1JsonOutputStream (yourWriter);

   for (;;) {

      // logic here to read name components from a DB or other medium

      ...

      // populate octet strings (assume first, second, third are byte arrays
      // populated by the above logic)

      data.first.value = first;
      data.second.value = second;
      data.third.value = third;

      // encode

      try {
         name.encode (encodeStream);

         // perhaps write some non-ASN.1 data to the stream?
         ...
      }
      catch (Asn1Exception e) {
         // handle error ..
      }
   }