I want to ask which piece of code is more efficient in Java? Code 1:
void f()
{
for(int i = 0 ; i < 99999;i++)
{
for(int j = 0 ; j < 99999;j++)
{
Second is better for speed.
Reason is that in the first case, the scope of j
is limited to the inner for
loop.
As such, the moment, the inner loop is completed, the memory for j
is de-allocated, and again allocated for the next iteration of the outer loop.
Because the memory allocation and deallocation take some time, even though it's on stack, the performance of the first one is slower.