Java: faster alternative to string (byte [])

I am developing a binary data downloader based on Java The data is transmitted via text - based protocol (Uu encoding) For network tasks, use the netty library Binary data is split into thousands of small packets by the server and sent to the client (i.e. Java application)

Whenever I receive a new message (data), I receive a channelbuffer object from netty Now I need to process this data. Among other tasks, I need to check the header of the package from the server (such as HTTP status line) To do this, I call channelbuffer Array() to receive a byte [] array I can convert this array into a string through a new string (byte []), and easily check (for example, compare) its contents (again, compare with the "200" status message in HTTP)

The software I'm writing is using multiple threads / connections to receive multiple packets from parallel netty

This usually works, but when analyzing applications, I noticed that when the connection to the server is good and the data entry speed is very fast, this conversion to string objects seems to be a bottleneck In this case, the CPU utilization is close to 100%. According to the analyzer, it takes a lot of time to call the string (byte []) constructor

I searched for a better way to get a string from channelbuffer and noticed that the former also has a toString () method However, this method is even slower than the string (byte []) constructor

So my question is: does anyone know a better alternative to what I'm doing?

Solution

Maybe you can skip string conversion completely? You can use constants to hold byte arrays of comparison values and check the array to array instead of string - to - string

Here are some quick codes At present, you are doing something like this:

String http200 = "200";
// byte[] -> String conversion happens every time
String input = new String(ChannelBuffer.array());
return input.equals(http200);

Maybe it's faster:

// Ideally only convert String->byte[] once.  Store these
// arrays somewhere and look them up instead of recalculating.
final byte[] http200 = "200".getBytes("UTF-8"); // Select the correct charset!
// Input doesn't have to be converted!
byte[] input = ChannelBuffer.array();
return Arrays.equals(input,http200);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>