During the code review, maybe your boss will tell you that string creation should be placed outside the loop.
for(int i = 0; i < length; i++) {
String s = new String(i);
}
why?
Because while looping, too many temporary objects are created. Each time through the loop, it is required new String()
and assigned to a new object s
. We can make the following improvements:
String s;
for(int i = 0; i < length; i++) {
s = String.valueOf(i);
}
This avoids creating the object string each time through the loop s
.
There Java
are a lot of other places in here with these little details:
1. Remember the case given in [Effective Java] Article 1: Consider using static factory methods instead of constructors 1Boolean
?
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
Compared with the new Boolean(String s)
constructor method, the sums valueOf
returned by the method are all built-in objects, not the same as the constructor method, which will create a new object every time it is called .TRUE
FALSE
Boolean
== Therefore, when you see that a class has both a constructor and a static constructor in the future, check the implementation of the static constructor, which may save a lot of resources. ==
HashMap
keySet
method that returnsMap
all the forms inkey
.Set
Looking at the code, you will find that what is here isSet
actuallyAbstractMap
a member variable in .Java
There is also a situation in which unnecessary objects are implicitly created. Everyone knows thatint
andInteger
,long
andLong
can be converted to each other (autoboxing and unboxing). for example:
public static void main(String[] args) {
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
There is no problem with this code, but the objects that are not needed to create the pen are hidden in the middle. Since it sum
is declared as a Long
type, each loop operation needs to be sum
converted to a Long
type, which increases the creation of objects. In fact, you just need to Long sum = 0L
change it long sum = 0L
to .
== Therefore, in program development, try to avoid the interaction of basic types and boxed types to prevent the creation of unnecessary objects. ==
Having said so much, it is not to let everyone avoid creating objects in development. In fact, most objects can be created directly, but you need to pay attention to the process of looping, boxing, and object creation is very time-consuming to avoid wasting unnecessary resources.