Is using List <Byte> not a good idea?

I need to rewrite C ++ code in Java that I wrote years ago.

In C ++, I used std::vector<unsigned char> buffer

to implement a buffer that I would fetch from the socket connection.

In this buffer, I perform all kinds of operations:

  • Have an iterator to buffer the item and advance as needed.
  • Find it for specific tokens.
  • Get a range of byte elements (subbuffer) from a buffer using indices / iterators.

Based on these requirements, I could use ArrayList<Byte>

and have my own iterator-like class to keep track of the current item and work using indexes.

How would it be ineffective to use List<Byte>

?

I've seen it somewhere else ByteBuffer

but my requirements don't require it.

Possibly because I need indexes, lookups, etc. and my buffer will not change or change once it is created.

I only need to read the buffer and perform the above operations.

Should I be better off having a wrapper around byte[]

with my own iterator / pointer class?

+3


source to share


2 answers


It really depends on your requirements. The huge problem with this List<Byte>

is that you are using Byte

objects, not primitive values Byte

!

This not only affects memory consumption, but also means that there can be a lot of boxing / unboxing . This can lead to the creation of a large number of objects † - leading to a constant drain of the garbage collector.

So, if you intend to do computationally intensive or work with huge amounts of data, then the class ByteBuffer

has different performance advantages here.




† from Java Language Specification Β§5.1.1

The above rule is a pragmatic tradeoff requiring that certain shared values ​​always be included in indistinguishable objects. An implementation can cache these, lazily or impatiently .

+3


source


List

is not a class, it is an interface, so you need to provide the actual class behind it to provide an implementation. You can use a variable List<Byte>

in your code to hide the implementation details of the actual class you are using, but if you need it to behave like an array sometimes, but as a list of others (iterators, etc.), then you don't need abandon the class ArrayList<Byte>

and keep using it to be able to use the index and list behavior together. If you switch to List<Byte>

, you finally end up doing unnecessary roles to access the array functions ArrayList

, and they will consume CPU by checking that the class is different. And you blur the code. Also, you have alternatives in ByteBuffer

orCharBuffer

as suggested by other answers. But be careful what this class is abstract

, so you will have to implement some of them before you can use.



0


source







All Articles