Thiemos Archiv
- Friday, 2012-05-11 22:02
- 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 als1 << a
. Das funktioniert natürlich nur mit ganzzahligen Exponenten.Math.pow(a, 3)
ist 1000 mal langsamer alsa * a * a
.Math.pow(a, 2)
ist 100 mal langsamer alsa * 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 alsa < 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)
with1 << a
(warning, this works with integers only) andMath.pow(a, 3)
witha * a * a
. Both are 1000 times faster. - Replace
Math.pow(a, 2)
witha * a
. This is 100 times faster. - Try to replace
Math.round(d)
with(int) (d + 0.5)
andMath.floor(d)
with(int) d
but keep in mind this works for positive numbers only.
Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.
double c = 3.14;
c = c<<1;
c = Math.pow(c, 2);