Skip to main content

Bulk Put(int) for ByteBuffer

No replies
Cornix
Offline
Joined: 2013-07-20
Points: 0

Hi.

Edit: The problem has been solved. I needed to flip the IntBuffer instead of the ByteBuffer.

I have a little problem with a direct ByteBuffer.

I am trying to put an array of int values into a ByteBuffer but the ByteBuffer does not offer a method to do so directly.
My own performance tests have shown, that iterating through an int array and putting each int individually leads to drastic performance loss compared to using an IntBuffer and putting the entire array at once.
But performance is very important in this specific part of my application and to keep the code clean I would prefer to only use ByteBuffers.

I was trying to cheat a little and did the following:

<br />
	public static ByteBuffer makeByteBuffer(int[] data) {<br />
		ByteBuffer buffer = ByteBuffer.allocateDirect(data.length * INTEGER_BYTE_SIZE).order(ByteOrder.nativeOrder());<br />
		IntBuffer buf = buffer.asIntBuffer();<br />
		buf.put(data);<br />
		buffer.flip();<br />
		return buffer;<br />
	}

In comparison, this code works and will not throw an error but is siginificantly slower:
<br />
	public static ByteBuffer makeByteBuffer(int[] data) {<br />
		ByteBuffer buffer = ByteBuffer.allocateDirect(data.length * INTEGER_BYTE_SIZE).order(ByteOrder.nativeOrder());<br />
		for (int i = 0; i < data.length; i++) {<br />
			buffer.putInt(data[i]);<br />
		}<br />
		buffer.flip();<br />
		return buffer;<br />
	}

But this just got me a fatal error when trying to use the ByteBuffer:
Quote:

#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00000000669b09e5, pid=9132, tid=7664
#
# JRE version: 7.0_07-b11
# Java VM: Java HotSpot(TM) 64-Bit Server VM (23.3-b01 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C [atio6axx.dll+0xac09e5] atiPS+0x840475
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

So my question is, what exactly is the correct way of realising a bulk put method for ints on a ByteBuffer with good performance?
Or is there any fast and efficient way to cast an IntBuffer into a ByteBuffer maybe?

Thank you very much.