Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time required in java

i would like to know how much time is required to execute the conditional loops individually. Like if i had an option to use "if else", "while","for", or "foreach" loop then which loop would get executed faster.I know the difference would be very small and most would say that it would not matter but if i were to have a program which would access thousands of data then this point would come into picture.

I would like to know if i declare a variable in the beginning in java and if i were to declare it just before i use it will it make any difference. will the total time required be reduced? if yes then which is practically used (the one in which variables are declared in the beginning or where they are just declared b4 they are used)?

like image 452
Amol Avatar asked Feb 25 '26 00:02

Amol


2 Answers

Stop micro-optimizing.

Spend your time on finding the best algorithms, the best data structures, and the best design for your system, and writing the most readable code. Not on these little things.

like image 131
polygenelubricants Avatar answered Feb 27 '26 12:02

polygenelubricants


There is not much point trying to hand-optimize your code - the JIT compiler is likely to do a lot better job than you. Not the least because it will have much more information about the exact environment at the point of execution than you can ever have before compilation.

Moreover, since optimizers are tuned for the "common case", introducing uncommon optimizations to your code may actually make it less optimizable by the JIT compiler, thus slower in the end.

Nevertheless, if you still really want to measure something, you can do it like this:

long before = System.currentTimeMillis();
// execute your code e.g. a million times
long after = System.currentTimeMillis();
System.out.println("Execution took " after - before " milliseconds");
like image 34
Péter Török Avatar answered Feb 27 '26 14:02

Péter Török