Tuesday, May 29, 2012

double conversion with GWT

During my photogrammetry project, I worked with java that was converted into javavascript with GWT and I found an interesting optimization to convert double into integers.


To convert a double into an int, there exists multiple approaches:

  • Cast to int
  • Math.floor
  • Math.round()
  • ~~x
  • x | 0

The three first items are well known and are common java. However as the project is compiled in javascript, we can use javascript specific language that can provide interesting options: 

  • "~~x" will do a 2 binary not operations on the natural part of x. In other words, not(not(x)) will return the content of the natural part of x. 
  • "x | 0" will do a logical of the natural part of x with 0. In other words, or(x,0) will return the natural part of x.
Be aware that these functions only work if x is greater or equal to 0...

It seems pretty trivial, however, we can see here: http://jsperf.com/math-floor-vs-math-round-vs-parseint/39  that running ~~x or x|0 is often faster than Math.floor(x)...

You will ask how to perform such javascript trick in GWT: for this, we must use JSNI:


    private static native int floor(double x) /*-{
return ~~x;
}-*/;

No comments:

Post a Comment