How can I reduce memory consumption?
Here are a number of tips that help conserve memory:
- When possible, allocate all applet resources in the constructor. This is interesting for two reasons. First, if there's not enough memory to install your applet, you'll know immediately. This is much better than to face a memory allocation at runtime, when the card has already been delivered Second, allocation memory means writing to the EEPROM, which is slow.
- The Java Card standard doesn't require garbage collection. So unless you are willing to waste memory, you have to keep track your old objects and reuse them. Remember: the Java Card Virtual Machine runs "forever", so if an object becomes unreachable, its memory is gone "forever" (or at least until you delete the applet).
- Even if your platform provides proprietary garbage collection, you'd better reuse your objects. Allocating new objects is slow, and so is garbage collection. You get the point.
- Use a big buffer instead of several small buffers. Depending on how your platform allocates memory, 4 byte arrays of 32 bytes may eat more EEPROM than a unique byte array of 128 bytes.
- To avoid stack overflows: avoid deep class trees, reuse local variables and keep the number of parameters to the strict minimum.
Bottom line: it pays to recycle!