简体   繁体   中英

Is using List<Byte> not good idea?

I need to re-write some C++ code in Java that I wrote years ago.

In C++, I used a std::vector<unsigned char> buffer to implement a buffer which I would retrieve from a socket connection.

With this buffer I do all kinds of operations:

  • Have an iterator to buffer element and advance it as required.
  • Search it for certain tokens.
  • Get a range of byte elements (sub-buffer) from buffer using indexes / iterators.

Based on these requirements, I could use ArrayList<Byte> and have a custom iterator-like class to keep track of current element and work using indexes.

In what ways will be in-efficient to use List<Byte> ?

Somewhere else I have seen ByteBuffer being recommended but my requirements don't call for it.

Perhaps because I need indexes, searches to perform, etc. and my buffer won't change or be modified once created.

All I need is to read the buffer and perform above operations.

Should I better just have a wrapper around byte[] with my own iterator/pointer class?

This really depends on your requirements. The huge problem with List<Byte> is the fact that you are using Byte objects rather than primitive byte values!

Not only does that affect memory consumption, it also means that there might be a lot of boxing/unboxing going on. That may cause a lot of objects to be generated - leading to constant churn for the garbage collector.

So if you intend to do intensive computations, or you are working massive amounts of data, then the ByteBuffer class has various performance advantages here.


† from Java Language Specification §5.1.1

The rule above is a pragmatic compromise, requiring that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly .

List is not a class, it's an interface, so you need to supply an actual class behind it, to provide an implementation. You can use a List<Byte> variable on your code, to hide the implementation details of the actual class you are using, but if you need it behave as an array sometimes, and as a List others (whit iterators and such), then you need not to abandon the ArrayList<Byte> class and continue using it, to be able to use the index and list behaviours together. If you switch to a List<Byte> , finally you will end doing unnecessary casts to access the array features of ArrayList , and these will consume cpu, checking that the proper class is being cast. And you'll blur the code. Also, you have alternatives in ByteBuffer or CharBuffer , as suggested by other responses. But beware that these class are abstract , so you'll have to implement part of them, before being able to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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