Isn’t it just great how a few simple tricks can speed up your code? Here are some…
Al examples below are based on the fact that calling a method is way slower than just calculating the answer on the fly.
Here are some fast ways to replace common Math methods. In most cases this save half the time or more
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | //slow: z = Math.abs(x); //faster: z = (x<0) ? -x : x; //slow: z = Math.min(x,y); //faster: z = (x<y) ? x : y; //slow: z = Math.max(x,y); //faster: z = (x>y) ? x : y; //slow: z = Math.floor(x); //faster: z = (x >>> 0); //slow: z = Math.ceil(x); //faster: z = (x >>> 0) + 1; //mind the brackets! //slow: z = Math.round(x); //faster: z = int(x); //slow: z = Math.pow(x,2); //faster: z = x*x; //this one only works faster if the power is a fixed value; for-loops in case of a variable power are most of the time slower than the Math.pow! |
Of course most of the above method replacements make your code more sloppy, so I suggest you only use these replacements when the speed of the application really matters (for example in huge for-loops) or in libraries or components which rarely need adjustment.
If you have any good additions to this list please let me know…


