Fast Java classes ByteBuffer / IntBuffer / ShortBuffer?

I am working on an Android application (obviously in Java) and have recently updated my UDP reader code. In both versions, I configured several buffers and received a UDP packet:

byte[] buf = new byte[10000];
short[] soundData = new short[1000];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);

In the original version, I put the data back one byte at a time (this is actually 16 PCM audio data):

for (int i = 0; i < count; i++)
    soundData[i] = (short) (((buf[k++]&0xff) << 8) + (buf[k++]&0xff));

In the updated version, I used some cool Java tools that I did not know about when I started:

bBuffer  = ByteBuffer.wrap (buf);
sBuffer  = bBuffer.asShortBuffer();
sBuffer.get (soundData, 0, count);

"" ( ). , , - , , . , JVM-, , , , , , .

, Java NIO, , , mo 'betta' .

- , Java UDP- " "??

, R.

+5
3

, , , , ..

, : , ..

- . . , .

Android, , . . TraceView.

+1

, ( ), ByteBuffer ( ) ShortBuffer ( ) .

, DatagramChannel.socket(), , socket.getChannel(), DatagramChannel. ByteBuffer ( ByteBuffer.allocateDirect ). asShortBuffer() , ShortBuffer ByteBuffer.

:

 DatagramSocket socket = DatagramChannel.socket();
 // code to connect socket
 DatagramChannel channel = socket.getChannel();
 ByteBuffer buffer = ByteBuffer.allocateDirect (10000);
 // you may want to invoke buffer.order(...) here to tell it what byte order to use
 ShortBuffer shortBuf = buffer.asShortBuffer();

 // in your receive loop:
 buffer.clear();
 channel.receive(buffer);
 shortBuf.position(0).limit(buffer.position()/2); // may ignore a byte if odd number received
 shortBuf.get(soundBuf,0,shortBuf.limit());

, , , , , , . , ( , Android , , , -, , ), shortBuf.get() .

+3

DataInputStream , ByteArrayInputStream, . readShort() ByteBuffer.

Alternatively, you can read directly in DirectByteBuffer through the DatagramChannel, rather than using DatagramPacket and DatagramSocket. You are currently using a mixture of java.net and java.nio.

I would not expect major performance differences between the two approaches, but I would expect both to be faster than your hybrid approach.

0
source

All Articles