简体   繁体   English

我们可以直接在Java的字节缓冲区中读取对象吗?

[英]could we read an object directly into the bytebuffer in java?

说我有一个List<Integer> ls ,我知道它的长度可以为字节缓冲区分配length * 4个字节,并使用putltil将ls直接读入缓冲区吗?

This should do what you're looking for: 这应该可以满足您的需求:

ByteBuffer buffer = ByteBuffer.allocate(ls.size()*4);
for (Integer i: ls)
    buffer.putInt(i);

One caveat: This function assumes that your list does not contain any null -entries. 一个警告:此函数假定您的列表不包含任何条目。

I don't think you can do much better than this, since the underlying array of Integer objects in ls is an array of references (pointers) to these Integer objects rather than their contained int -values. 我认为您不能做得更好,因为lsInteger对象的基础数组是对这些Integer对象的引用(指针)数组,而不是它们包含的int -values。 The actual Integer objects will reside in memory in some random order, dictated roughly by when they were created. 实际的Integer对象将以某种随机顺序驻留在内存中,大致取决于创建它们的时间。 So, it's unlikely that you would find some consecutive block of memory that contains the data that you would need to copy into your ByteBuffer (I think this is what you meant by "directly reading" it.). 因此,不太可能找到连续的内存块,其中包含需要复制到ByteBuffer (我认为这是“直接读取”它的意思。) So, something like using sun.misc.Unsafe will probably not be able to help you here. 因此,使用sun.misc.Unsafe类的东西可能无法在这里为您提供帮助。

Even if you had an int[] instead of a List<Integers> you probably won't be able to reliably read the data directly from memory into your ByteBuffer , since some JVM's on 64-bit machines will align all values on 64-bit address-locations for faster access, which would lead to "gaps" between your ints . 即使您使用int[]而不是List<Integers>您也可能无法将数据直接从内存中可靠地读取到ByteBuffer ,因为64位计算机上的某些JVM会将64位计算机上的所有值对齐地址位置以加快访问速度,这将导致ints之间的“间隙”。 And then there is the issue of endianness , which might differ from platform to platform... 还有一个问题, 字节序可能因平台而异...

Edit: 编辑:

Hmmm... I just took a look at the OpenJDK source-code for the putInt()-function that this would be calling... It's a horrendous mess of sub-function-calls. 嗯...我只是看了将要调用的putInt()函数OpenJDK源代码 ...子函数调用真是一团糟。 If the "sun"-implementation is as "bad", you might be better off to just do the conversion yourself (using shifting and binary-ops) if you're looking for performance... The fastest might be to convert your Integers into a byte[] and then using ByteBuffer.wrap(...) if you need the answer as a ByteBuffer . 如果“ sun”实现很糟糕,那么如果您要寻找性能,最好自己进行转换(使用shift和binary-ops)...最快的方法可能是转换Integers转换为byte[] ,然后如果需要答案作为ByteBuffer ,则使用ByteBuffer.wrap(...) Let me know if you need code... 让我知道您是否需要代码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM