我有几个问题:
Regarding the creation of References to Objects and primitive values, I was wondering: when is it usually appropriate to store values in a variable?
From my general knowledge, the rule of thumb would be to create references when the same value is used more than once or to avoid hard-coding E.g.
String name = "Bob"; System.out.println("Welcome " + name + ". Is your name really " + name + "?");
Whereas if it is only used once like in the example below, it would be more performant to simply do the following.
System.out.println("Welcome Bob");
as opposed to
String name = "Bob"; System.out.println("Welcome " + name + ".");
Added question: If we are talking about a variable that is used when iterating over an array or enumerable object, which of the following would be more performant (assuming we are looping over an object like 1 million times)? Or would there be no difference and is simply a stylistic choice?
For example,
// nameArray is an extremely long array public static void loop(String[] nameArray) { String name; //Should this be declared inside the loop? int len = nameArray.length(); for(int i = 0; i < len; i++) { name = nameArray[i]; System.out.println(name); } }
or would this be more preferred?
// nameArray is an extremely long array public static void loop(String[] nameArray) { int len = nameArray.length(); for(int i = 0; i < len; i++) { String name = nameArray[i]; //Declare String reference inside for loop System.out.println(name); } }
In regards to garbage collection, after a reference to an object/primitive has passed its useful life, is it always good practice to set that value to null to make it eligible for garbage collection (assuming that there are no other references to that object/primitive value) ?
For example,
String name = "Bob"; System.out.println("Welcome " + name + ".); name = null;
name
是一个局部变量,将其设置为null并不会有太大的影响,因为它的生命周期已经结束了。 - SomeJavaGuy