Many common Java performance problems originate from the idea of class design in the early stages of the design process, as early as many developers began to consider performance issues. in this series, Brian Goetz discusses common Java performance risks and how to avoid them during design. in the second part, he discussed some techniques to reduce temporary object creation.
Although many programmers delay performance management until the end of the development process, performance considerations should be combined with the design cycle from the first day. this series explores some early design ideas that can greatly affect application performance. in this article, I continue to explore the issues of creating a large number of temporary objects and provide some techniques to avoid them.
A temporary object is a short-lived object. It is generally used to save other data and has no other purpose. programmers generally use temporary variables to pass data to a method or return data from a method. the first part discusses how the temporary object brings negative impact to the performance of a program, and how the design ideas of some class interfaces provide the creation of temporary objects. without the creation of those interfaces, you can greatly reduce the need to create temporary objects that affect your program performance.
OnlyStringSay no?
When it wants to create a temporary variable, the String class is one of the largest sinners. for demonstration, I wrote a regular expression matching example in the first part. By comparing it with a similar but carefully designed interface, demonstrate how the seemingly harmless interface causes the creation of a large number of objects, which is several times slower. here is the original and better class interface:
Example of bad regular expression matching:
Public class BadRegExpMatcher {
Public BadRegExpMatcher (String regExp );
Public String match (String inputText );
}
Example of regular expression matching:
Class BetterRegExpMatcher {
Public BetterRegExpMatcher (...); // Some
Public int match (String inputText );
Public int match (char [] inputText );
Public int match (char [] inputText, int offset, int length );
Public int getMatchLength ();
Public String getMatchText ();
}
A large number of programs that use BadREgExpMatcher are much slower than those that use BtterRegExpMatcher. first, the caller has to create a String to pass in match (), and then match () creates a String to return the matched text. the result is that there are two objects created for each call, which do not seem to be much, but if you need to call match () frequently, the cost of creating these objects will be too high. badRegExpMatcher's performance problem is not in its implementation, but its interface; like its defined interface, there is no way to avoid the creation of some temporary variables.