Format MAC address in Android / Java without creating unnecessary junk

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?

+4
source share
2 answers

Instead of using String.format() , which is quite expensive, just manually add the pieces. Unfortunately, numbers and letters are not adjacent in ASCII / UTF-8, so here is how I would handle this:

 static final char HEX_DIGITS[] = "01234567890abcdef".toCharArray(); ... hex_sb.append(HEX_DIGITS[thisByte >> 4]).append(HEX_DIGITS[thisByte & 0xf]); 

Since this is a MAC address (known length) and gets a lot of names, I would probably expand it all, including adding a colon / period (which should be char , not String ). If this is really critical, control your char[] and pass it to String#new(char[]) . You could avoid reinstalling the delimiters this way.

+3
source

Each new MAC will need a new String, you will not be able to use it, since String is unchanged. As for manipulating StringBuilder, it does not create any garbage, since StringBuilder will reuse the same char array with setLength (0) and append, it will only change the current position. The only thing that could help is to work with StringBuilder directly, without converting it to String, if possible.

+1
source

Source: https://habr.com/ru/post/1498793/


All Articles