maettig.com

Thiemos Archiv

Kleine Merkliste zur Performanz der Math-Funktionen in Java:
  • In den meisten Fällen lohnt es sich nicht, über die Optimierung mathematischer Ausdrücke nachzudenken, außer sie werden in Schleifen viele tausend mal ausgeführt. Andere Programmteile wie etwa Datenbankzugriffe oder die Bildschirmausgabe haben meist einen viel größeren Einfluss auf die Gesamtperformanz.
  • Math.pow(2, a) ist 1000 mal langsamer als 1 << a. Das funktioniert natürlich nur mit ganzzahligen Exponenten.
  • Math.pow(a, 3) ist 1000 mal langsamer als a * a * a.
  • Math.pow(a, 2) ist 100 mal langsamer als a * a.
  • Math.round(d) ist 80 mal langsamer als (int) (d + 0.5). Aber Achtung, das funktioniert nur für positive Zahlen.
  • Math.floor(d) ist 50 mal langsamer als (int) d. Aber Achtung, das funktioniert nur mit positiven Zahlen.
  • Math.abs(a) ist 10 mal langsamer als a < 0 ? -a : a.

English:

  • Don't waste your time with optimizing this Math stuff if you are not sure this is your bottleneck. Check your database queries and your rendering code first.
  • Replace Math.pow(2, a) with 1 << a (warning, this works with integers only) and Math.pow(a, 3) with a * a * a. Both are 1000 times faster.
  • Replace Math.pow(a, 2) with a * a. This is 100 times faster.
  • Try to replace Math.round(d) with (int) (d + 0.5) and Math.floor(d) with (int) d but keep in mind this works for positive numbers only.
The problem is, the Java Math library works on doubles, and this doesn't compile:
double c = 3.14;
c = c<<1;
c = Math.pow(c, 2);
Roy van Rijn
@Roy: I know. As I wrote above (in German) some of these replacements work with positive integers only. But in many, many cases you are doing this with integers anyway. Besides, your example is strange. Simply make it c * c. This works in all cases.
Thiemo

Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.

[ ← Zurück zur Übersicht ]

Impressum & Datenschutz