Skip to content
Advertisement

In Java, how to copy data from String to char[]/byte[] efficiently?

I need to copy many big and different String strs’ content to a static char array and use the array frequently in a efficiency-demanding job, thus it’s important to avoid allocating too much new space.

For the reason above, str.toCharArray() was banned, since it allocates space for every String.

As we all know, charAt(i) is more slowly and more complex than using square brackets [i]. So I want to use byte[] or char[].

One good news is, there’s a str.getBytes(srcBegin, srcEnd, dst, dstBegin). But the bad news is it was (or is to be?) deprecated.

So how can we finish this demanding job?

Advertisement

Answer

I believe you want getChars(int, int, char[], int). That will copy the characters into the specified array, and I’d expect it to do it “as efficiently as reasonably possible”.

You should avoid converting between text and binary representations unless you really need to. Aside from anything else, that conversion itself is likely to be time-consuming.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement