I suggest you check this out. This is a fairly expensive operation if you need to do this many times, but it can be cheaper than Double.toString () or Integer.toString () if you used them to create data in the first place.
I also suggest using only double if you don't know that using float never cause a rounding problem .;)
It's about as expensive as creating objects like String, or adding an entry to a HashMap. If you do not plan to avoid this, I would not worry about it.
EDIT: As with the @Stackers test, I would continue the test and use nanoTime ()
int runs = 10000000; String val = "" + Math.PI; long start = System.nanoTime(); for (int i = 0; i < runs; i++) Float.parseFloat(val); long time = (System.nanoTime() - start) / runs; System.out.println("Average Float.parseFloat() time was " + time + " ns."); long start2 = System.nanoTime(); for (int i = 0; i < runs; i++) Double.parseDouble(val); long time2 = (System.nanoTime() - start2) / runs; System.out.println("Average Double.parseDouble() time was " + time2 + " ns.");
prints
Average Float.parseFloat() time was 474 ns. Average Double.parseDouble() time was 431 ns.
BTW: I have a function that reads doubles from a direct ByteBuffer, which takes 80 ns. This is faster because it does not need a string, and it does not create any objects. However, this is by no means trivial, and you should develop your basic system to avoid creating any object.;)
source share