#Is instantiating a variable without assigning it to a variable a tool to reduce the instanc lifetim?

1 messages · Page 1 of 1 (latest)

delicate mist
#

If my question was not clear, I'll try to make it as an example:

Is

private void methodName() {
    System.out.println(new SecureRandom.nextInt(10));
    /*Lets suppose that we have 10-15 more lines of code here*/
}

More efficient than

private void methodName() {  
    SecureRandom sr = new SecureRandom();
    System.out.println(sr.nextInt(10));
    /*Lets suppose that we have 10-15 more lines of code here*/
}

?

Will any of them be gc first? Will any of them, in this or in another situation, have a shorter lifetime? Or both will depend of the block scope they are inserted?

clever basaltBOT
#

<@&987246841693360200> please have a look, thanks.

clever basaltBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

manic wasp
#

no speed difference

#

lifetime is different, yes

#

the "anonymous object" is eligible for GC right after usage

#

with the var, its not

#

unless u null out the var

delicate mist
#

Got it

#

So right after I use it, it will be garbage collected

#

Thanks zabuzard 👍

manic wasp
#

unlike c++, objects are killed at some point in the future. not immediately when they could

#

(this is a massive performance saver)

delicate mist
#

Got it

#

Tx