0

I've inspected the code of .round(float a) static method of the java.lang.Math class and I see that it's using binary shifting operations to conduct the rounding. It's probably well optimized and fast, but I wonder on how does it compare to the standart integer casting conversion (int) a. Assuming I have such operation:

float x = 1.8F;
int a = (int) x; // a = 1
int b = Math.round(x); // b = 2

As you can see, b is more accurate rounding and I would prefer it, however in terms of performance is it significantly slower (if at all), than the casting? Assummıng I have >10,000 operations per second.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
  • 2
    You can do 10,000 such operations in much less than a second on a modern computer. Make sure you're not trying to optimise unnecessarily. – khelwood Dec 12 '19 at 22:53
  • @khelwood in my case it might not be necessarily a modern computer, maybe a less capable device, an android device with abismal CPU (for example a pocket book reader) – Sergey Emeliyanov Dec 12 '19 at 22:55
  • 3
    Then you need to try it out. But `Math.round` is unlikely to be the thing that slows down your program. – khelwood Dec 12 '19 at 22:58
  • @khelwood I don't have a way to put my hands on the device right now, also want to hear a scientific (maybe a link to read) answer from experienced in this area, hence the question. – Sergey Emeliyanov Dec 12 '19 at 23:00
  • 2
    It is pointless to compare them, as they do different things. It would be more to the point to compare casting with `Math.floor()`. – user207421 Dec 12 '19 at 23:37
  • 1
    @user207421 I clearly pointed out, that I understand how they are different. I need to make a choice, as if I actually want to go for precision rounding at the cost of performance, and to what extent. – Sergey Emeliyanov Dec 12 '19 at 23:39
  • 1
    There are some hints about how to approach such a question and how a in depth answer might look like [here](https://stackoverflow.com/questions/58995731/java-manually-unrolled-loop-is-still-faster-than-the-original-loop-why/58996346#58996346), if you're interested in that. proper bench marks, byte-code, jit compiled machine code, hardware optimization and what not – Curiosa Globunznik Dec 12 '19 at 23:42
  • 1
    @SerjArdovic Have you profiled your application yet?. – WJS Dec 12 '19 at 23:43
  • @gurioso thank you, this is an interesting investigation there. – Sergey Emeliyanov Dec 12 '19 at 23:45
  • @WJS I am currently deciding with which path I should take, perhaps I will go with a prototype and conduct testing and profiling. – Sergey Emeliyanov Dec 12 '19 at 23:46
  • I guess, both boil down to a single CPU instruction taking maybe ten cycles. So you can do millions of them per second easily. One of them may be faster, but the difference can be hard to spot in any real code. There's no reason to assume that the cast is faster. – maaartinus Dec 14 '19 at 19:21

0 Answers0