I am working on an Android application that should process thousands of packets per second while extracting and formatting the MAC address of each frame. The problem is that the garbage collector runs dozens of times per second and stops my application, which in turn makes me skip packets. I avoided creating new objects as much as possible (I think).
I used the distribution tracker in DDMS and determined that 99% of the garbage being cleaned comes from the following method. Here is the code I'm using:
void parseMac() { hex_sb.setLength(0); for (hex_counter = 0; hex_counter < 6; hex_counter++) { hex_sb.append(String.format("%02X", parser_packet_bytes[parser_skip + hex_counter])); if (!(hex_counter == 5)) { hex_sb.append(":"); } } formatted_mac = hex_sb.toString(); }
hex_sb is a StringBuilder that is reused. hex_counter is the number of bytes in the MAC address (bytes come from parser_packet_bytes, byte []). If this is not the last byte of the MAC, add ":" for proper formatting. formatted_mac is a class string containing a formatted MAC. According to the distribution tracker, the only problem is the string using String.format.
My question is to StackOverflow experts: how can I rewrite the above method to create less (preferably no) garbage?
source share