Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm speed with double and int?

how do algorithms with double compete compared to int values? Is there much difference, or is it neglectable?

In my case, I have a canvas that uses Integers so far. But now as I'm implementing a scaling, I'm probably going to switch everything to Double. Would this have a big impact on calculations? If so, would maybe rounding doubles to only a few fractions optimize performance?

Or am I totally on the path of over-optimization and should just use doubles without any headache?

like image 745
membersound Avatar asked Apr 30 '13 11:04

membersound


2 Answers

You're in GWT, so ultimately your code will be JavaScript, and JavaScript has a single type for numeric data: Number, which corresponds to Java's Double.

Using integers in GWT can either mean (I have no idea what the GWT compiler exactly does, it might also be dependent on context, such as crossing JSNI boundaries) that the generated code is doing more work than with doubles (doing a narrowing conversion of numbers to integer values), or that the code won't change at all.

All in all, expect the same or slightly better performance using doubles (unless you have to later do conversions to integers, of course); but generally speaking you're over-optimizing (also: optimization needs measurement/metrics; if you don't have them, you're on the “premature optimization” path)

like image 78
Thomas Broyer Avatar answered Sep 21 '22 05:09

Thomas Broyer


There is a sizable difference between integers and doubles, however generally doubles are also very fast.

The difference is that integers are still faster than doubles, because it takes very few clock cycles to do arithmetic operations on integers.

Doubles are also fast because they are generally natively supported by a floating-point unit, which means that it is calculated by dedicated hardware. Unfortunately, it generally is usually 2x to many 40x slower.

Having said this, the CPU will usually spend quite a bit of time on housekeeping like loops and function calls, so if it is fast enough with integers, most of the time (perhaps even 99% of the time), it will be fast enough with doubles.

The only time floating point numbers are orders of magnitude slower is when they must be emulated, because there is no hardware support. This generally only occurs on embedded platforms, or where uncommon floating point types are used (eg. 128-bit floats, or decimal floats).

The result of some benchmarks can be found at:

  • http://pastebin.com/Kx8WGUfg
  • https://stackoverflow.com/a/2550851/1578925

but generally,

  • 32-bit platforms have a greater disparity between doubles and integers
  • integers are always at least twice as fast on adding and subtracting
like image 22
ronalchn Avatar answered Sep 19 '22 05:09

ronalchn