Little Java Tricks

I have been developing in java for many years and have seen quite a lot of other people's code. It is not strange, but constantly from one project to another I see the same problems. This topic is an attempt at educational program in the most commonly used language constructs. Part of what is described is pretty banal things, however, as my experience shows, all these platitudes are still relevant. I hope this article is useful to many java programmers. So, let's go:

new vs valueOf

//медленно
Integer i = new Integer(100);
Long l = new Long(100);
String s = new String("A");
//быстро
Integer i = Integer.valueOf(100);
Long l = 100L;//это тоже самое что Long.valueOf(100L);
String s = "A";


Try to always use the valueOf method instead of the constructor in standard wrapper classes of primitive types, unless you need to specifically allocate memory for a new value. This is because all of them, except floating point numbers, from Byte to Long, have a cache. By default, this cache contains values ​​from -128 to 127. Therefore, if your value falls into this range, the value will be returned from the cache. The value from the cache gets 3.5 times faster than when using the constructor + memory saving. In addition, the most commonly used values ​​can also be cached by the compiler and the virtual machine. If your application often uses integer types, you can increase the cache for Integer through the system property “java.lang.Integer.IntegerCache.high”, as well as through the virtual machine parameter -XX:.

+ vs append

//медленно
String[] fields = new String[] {"a","b","c","d","e","f","g"};
String s = "";
for (int i = 0; i < fields.length; i++) {
	s = s + fields[i];
}
return s;
//быстро
String[] fields = new String[] {"a","b","c","d","e","f","g"};
StringBuilder s = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
	s.append(fields[i]);
}
return s.toString();


Never use the concatenation operations (operator +) of a string in a loop, especially if you have a lot of such operations, this can very significantly reduce performance. All this happens because in the above example “s = s + fileds [i]”, as many as 3 operations are performed: a StringBuilder is created based on the string s, the append concatenation method is called, the toString method is called after concatenation (it looks like this: s = new StringBuilder (s) .append (fields [i]). toString ();). As many as 3 operations instead of one! In addition, each result s + fileds [i] will occupy memory on the heap, as a separate line.

StringBuilder vs StringBuffer

Always use a StringBuilder, unless you need to use a specific StringBuffer, since StringBuilder has no synchronized methods, unlike StringBuffer, and therefore performance will be higher, although not significantly.

instanceOf

Try to use the instanceOf operator as little as possible. This is one of the slowest java operators and you need to be careful when using it. Keep in mind - most often the presence of this operator in the code means a lack of understanding of the principles of OOP, rather than an attempt to implement a certain pattern. Almost always polymorphism can help get rid of this operator.
PS Many in the comments appeal to "This is one of the slowest java operators." It really is. Of course, it is not entirely correct to compare language operators in terms of performance, since they perform completely different tasks, but, nevertheless, the mechanism of operation of instanceOf is much more complicated, for example, of the operator '*'.

Generics

//плохо
List a = new ArrayList();
//хорошо
List a = new ArrayList();


Always try to typify your collections, methods, and classes. This eliminates immediately 2 potential problems: type conversion and runtime errors. The purpose of such collections is also easier to understand. This is especially often neglected by my American-Hindu colleagues. If your collection should contain objects of different types - use , and even better then, knowing the common class / interface for all objects, you will not have to do type casting and use the instanceOf operator.

Interface for consts

//плохо
interface A {
	public static final String A = "a";
}
//хорошо
final class A {
	public static final String A = "a";
}

Interfaces for describing constants are very common. This is not correct from the point of view of OOP. The interface should describe the behavior, no more no less. This point is not very important, especially since the compilation result will be the same, but nevertheless java is an OOP language and it would be nice to adhere to its principles.

Override

Try to use Override annotation for methods that override superclass methods. This allows you to immediately avoid typos and increases the readability of the code (it allows you to immediately understand that the super class has the same method without opening the parent class).

null vs empty

Always try to return empty collections instead of null values ​​in the methods of your business logic, this eliminates unnecessary null checks and makes the code cleaner. There are some great methods for this in the Collections class:
Collections.emptyList();
Collections.emptyMap();
Collections.emptySet();

In the comments, they ask for clarification of the application. Typical case:

Set docs = getDocuments(plan);
for (Document doc : docs) {
	sendMessage(doc.getOwner());
}
public static Set getDocuments(Plan plan) {
	//some logic
	if (isDoSomethingOk() && hasAccessToDocuments(user)) {
		return plan.getDocuments();
	}
	return Collections.emptySet();
}

Of course, this does not mean that this technique should be applied absolutely everywhere. Say, if you serialize objects, then null values ​​are better. Actually - "in the methods of your business logic" just means the application in logic, and not in the model.

Number conversion

//медленно
int a = 12;
String s = a + "";
//быстро
int a = 12;
String s = String.valueOf(a);

The situation is very similar to string concatenation.

conclusions

It goes without saying that applying such rules will not save you from a poorly thought out application model, a slow algorithm or not optimized queries, but adhering to these simple principles, you can not badly speed up the work of your programs without suspecting it.

Also popular now: