chrisapotek
chrisapotek

Reputation: 6227

Algorithm to convert a double to a char array in Java (without using objects like Double.toString or StringBuilder)?

Does anyone know where I can find that algorithm? It takes a double and StringBuilder and appends the double to the StringBuilder without creating any objects or garbage. Of course I am not looking for:

sb.append(Double.toString(myDouble));

// or

sb.append(myDouble);

I tried poking around the Java source code (I am sure it does it somehow) but I could not see any block of code/logic clear enough to be re-used.

Upvotes: 3

Views: 1988

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533880

I have written this for ByteBuffer. You should be able to adapt it. Writing it to a direct ByteBuffer saves you having to convert it to bytes or copy it into "native" space.

See public ByteStringAppender append(double d)

If you are logging this to a file, you might use the whole library as it can write around 20 million doubles per second sustained. It can do this without system calls as it writes to a memory mapped file.

Upvotes: 6

Related Questions