Re: Performance tuning on socket and message packaging
On Sep 6, 4:51 pm, Yao Qi <qiyao...@gmail.com> wrote:
Our java program uses socket to send a lot of data out, and the types of
these data are integer, long, and string. Before we send them out, we
have to transform integers, long, and string to a byte array(correct me,
if it is *not* necessary), and then send them out like this,
socket.getOutputStream().write(datas);
socket.getOutputStream().flush();
After some profiling, we find the performance bottleneck of our program
is in Util.int2bytes(int), which is called nearly 500,000 times,
public static byte[] int2bytes(int nNum)
{
byte[] bytesRet = new byte[4];
bytesRet[0] = (byte) ((nNum >> 24) & 0xFF);
bytesRet[1] = (byte) ((nNum >> 16) & 0xFF);
bytesRet[2] = (byte) ((nNum >> 8) & 0xFF);
bytesRet[3] = (byte) (nNum & 0xFF);
return bytesRet;
}
I also find that the "new" statement is very expensive. How could I
tune my program?
Another bottleneck is located on the socket write and flush. How could
I make socket part in my program efficient? Any comments are welcome.
Best Regards
--
Yao Qi <qiyaoltc AT gmail DOT com> GNU/Linux Developerhttp://duewayqi.googlepages.com/
linux: No such file or directory
You are currently doing:
+++++++
OutputStream out = socket.getOutputStream();
out.write(int2bytes(nNum));
+++++++
To avoid the new operation, you could replace it by:
+++++++++++++
OutputStream out = socket.getOutputStream();
writeInteger(nNum, out);
public static void writeInteger(int nNum, OutputStream)
{
out.write((byte) ((nNum >> 24) & 0xFF));
out.write((byte) ((nNum >> 16) & 0xFF));
out.write((byte) ((nNum >> 8) & 0xFF));
out.write((byte) (nNum & 0xFF));
}
+++++++++++++
However, you would need to provide also this function for the other
data types.
+++++++++++++++++++++++++++
I suggest using the DataOutputStream object, which handles data types:
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(nNum);
See:
http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.html
HTH,
DAvid