Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java speed and memory occupation "contest"

Tags:

java

I have a general question about Java.

What is better?

case 1:

a = method1(7);
b = method2(a);
c = method3(b);

or

c = method3(method2(method1(7)));

case 2:

String a = method1(1);
String b = method2(2);
String c = method3(3);
String d = a+b+c;

or

String d = method1(1)+method2(2)+method3(3);

I was wondering what would be better speed-wise... I guess the second way (on both) is better memory occupation-wise, but I always wondered if one was faster than the other or if they take same amount of time to execute. I'm making a program that calls the same function many times, so every milisecond counts!

If there is another category in which they can compete (except speed, etc.), tell me too!

like image 579
Karlovsky120 Avatar asked May 03 '26 03:05

Karlovsky120


1 Answers

There will be no discernable difference in the execution speed. The only distinction between the code that uses temporary variables for intermediate results is that you'd be able to see intermediate values in the debugger. Moreover, if the values of intermediate variables are not used after the call to the target function, good chances are that the compiler will optimize these variables out, producing an identical byte code.

like image 50
Sergey Kalinichenko Avatar answered May 05 '26 17:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!