Java Performance Optimization Tips II

Source: Internet
Author: User
Tags rehash

Before finishing a Java Performance optimization blog, Link Java performance optimization One, today to add a few
1. Take care of the cyclic traversal of JavaA list traversal in Java can be a lot more cumbersome than it looks. Take the following two code example: a:
  • Private final list<bar> _bars;for (bar bar: _bars) {    //do important stuff}
  • B:
  • Private final list<bar> _bars;for (int i = 0; i < _bars.size (); i++) {Bar bar = _bars.get (i);//do Important Stuff}
  • When code a executes, an iterator is created for the abstract list, and code B uses get (i) directly to get the element, eliminating the overhead of the iterator relative to code a.
  • In fact, there is a need for some trade-offs. Code a uses iterators to ensure that the time complexity of acquiring an element isO (1)(Using theGetNext ()AndHasnext ()method), the final time complexity isO (n)。 But for code B, every time the loop is called_bars.get (i)Time-consuming complexity of theO (n)(Assuming the list is a linkedlist), then the time complexity of the entire loop of the final code B isO (n^2)(But if the list inside code B isArrayList,Thatget (i)Time complexity of the method isO (1))。 So when deciding which traversal method to use, we need to consider the underlying implementation of the list, the average length of the list, and the memory used. If we need to optimize memory, plusArrayListIn most cases, the time complexity of the lookup isO (1), you can choose the method that code B uses.

  • 2. Estimate the size of the collection at initialization time

From this Java document we can see that "a HashMap instance has two factors that affect its performance: the initial size and load factor (load factor)." When the hash table size reaches the initial size and the load factor product, the hash table is rehash operation. If you want to store multiple mappings in a HashMap instance, we need to set a large enough initialization size to store the mappings more efficiently instead of letting the hash table grow automatically so that the rehash can cause performance bottlenecks. "


Often encounter the need to traverse aArrayListand save these elements to theHashMapGo inside and put thisHashMapInitializing the expected size avoids the overhead of re-hashing. The initialization size can be set to the input array size divided by the result value of the default load factor (take 0.7 here):
  • Pre-optimization code:
  • Hashmap<string,foo> _map;void addobjects (list<foo> input) {  _map = new hashmap<string, Foo> ();  for (Foo f:input)  {    _map.put (F.getid (), f);}  }

    Optimized code
  • Hashmap<string,foo> _map;void addobjects (list<foo> input) {_map = new hashmap<string, Foo> ((int) Math.ceil (Input.size ()/0.7)); for (Foo f:input) {_map.put (F.getid (), f);}}


  • 3. Calculation of deferred expressions

In Java, all method parameters are evaluated (left-to-right) before the method call, as long as the method argument is an expression. This rule will cause some unnecessary actions. Consider the following scenario: Use comparisonchain to compare two Foo objects. One advantage of using such a comparison chain is that as long as a CompareTo method returns a non-0 value in the comparison process, the entire comparison ends, avoiding a lot of meaningless comparisons. For example, the objects to be compared in this scenario are the first to consider their score, then position, and finally the _bar attribute:

public class Foo {private float _score;private int _position;private Bar _bar, public int compareTo (foo other) {return Co Mparisonchain.start (). Compare (_score, Other.getscore ()). Compare (_position, other.getposition ()). Compare (_ Bar.tostring (), Other.getbar (). toString ()). Result;}}

But this implementation is always a two String object to hold the value of bar.tostring () and Other.getbar (). toString (). Even if the comparison of the two strings may not be required. To avoid this overhead, you can implement a comparator for the bar object:

public class Foo {private float _score;private int _position;private Bar _bar;private final Barcomparator bar_comparator = New Barcomparator (); public int CompareTo (Foo other) {return Comparisonchain.start (). Compare (_score, Other.getscore ()). Compare (_position, Other.getposition ()). Compare (_bar, Other.getbar (), bar_comparator). result (); private static class Barcomparator implements comparator<bar> {@Overridepublic int compare (bar A, bar b) {return A.T Ostring (). CompareTo (B.tostring ());}}


4. Pre-compiling regular expressions

The operation of a string is considered a costly operation in Java. Fortunately, Java provides some tools to make regular expressions as efficient as possible. Dynamic regular expressions are relatively rare in practice. In the next example, each call to String.replaceall () contains a constant pattern applied to the input values. So we pre-compile this pattern to save CPU and memory overhead.

Before optimization:

  • private string transform (string term) {return outputterm = Term.replaceall (_regex, _replacement);}

  • After optimization:
  • Private final Pattern _pattern = Pattern.compile (_regex);p rivate string transform (string term) {return outputterm = _patte Rn.matcher (term). ReplaceAll (_replacement);}

5. Cache it as much as possible if you can

Storing the results in the cache is also a way to avoid excessive overhead. There are now several implementations of the LRU (Least recently used) cache algorithm.


6. The Intern method of string is useful, but it is also dangerous

The intern feature of String can sometimes be used instead of caching.

From this document, we can know:

"A Pool of strings, initially empty, is maintained privately by the class String. When the Intern method was invoked, if the pool already contains a string equal to this string object as determined by the Equals (Object) method, then the string from the pool is returned. Otherwise, this string object was added to the pool and a reference to this string object is returned ".

This feature is similar to caching, but there is a limitation that you cannot set the maximum number of elements that can be accommodated. Therefore, if these intern strings are not limited (for example, strings represent some unique IDs), then it can make memory consumption grow fast.


jason0539

Blog: http://blog.csdn.net/jason0539 (reprint please indicate the source)

Sweep code Follow me public number

Java Performance Optimization Tips II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.