Downcast a long to an int for timing optimization

by Retired on ‎02-16-2010 09:58 AM (2,155 Views)

Summary


This article applies to BlackBerry® wireless devices based on Java™.




Description


Timing is very important for some applications, such as games. Since time comparisons in these types of applications normally span a period no longer than a few seconds, you can downcast the long from a date to an integer as a possible optimization strategy.


The long is normally obtained via a call to Date.getTime() or System.currentTimeMillis(). Regardless of how the date is represented as a long, if the time frame of the comparisons is less than 24.85 days (i.e., 231 -1 milliseconds), then the contents of the first 32 bits of the long can be dropped by converting the long to an int. This conversion saves four bytes per instance.


Be cautious when performing this optimization. Approximately every 24.85 days, the 32nd bit of the long will be set to the value 1 and will remain so for approximately another 24.85 days (i.e., until the value of the first 32 bits doubles, thus pushing the 1 into the 33rd bit). The pitfall of having the 32nd bit set to 1 is that since this is the lead bit of the resulting int, the int should be interpreted as negative. This negative number will throw off timing calculations since it is expected that the next point in time is greater than the previous.


To counter this problem, you can refrain from using this optimization, or use ints whenever the casting yields a positive value and use longs whenever the casting yields a negative value.


You are recommended (unless the application is under extreme space limitations) to not use the optimization strategy outlined in this document. With the minimal space savings and the extra computations (the casting, the comparison, and the possible re-assignment), the benefits of this optimization do not necessarily outweigh the added complexity.