Efficient Counter in Java

Source: Internet
Author: User

reference:http://www.programcreek.com/2013/10/efficient-counter-in-java/Often need a counter to understand the frequency of something (e.g., words) from a database or text file. A counter can is easily implemented by using a HashMap in Java. This article compares different approaches to implement a counter. Finally, an efficient one would be concluded.

Update:check out Java 8 counter, writing a counter are just 2 simple lines now.

1. The Naive Counter

Naively, it can be implemented as the following:

String s = "One, three, and three three"; string[] SArr = S.split (""); Naive approach hashmap<string, integer> counter = new hashmap<string, integer> (); for (String A:sarr) {if (Counter.containskey (a)) {int oldValue = Counter.get (a); Counter.put (A, oldValue + 1);} else {Counter.put (A, 1);}}

In each loop, you check if the key is exists or not. If it does, increment the old value is 1, if not, set it to 1. This approach was simple and straightforward, but it was not the most efficient approach. This method was considered less efficient for the following reasons:

    • ContainsKey (), get () is called twice when a key already exists. That means searching the map twice.
    • Since Integer is immutable, each loop would create a new one for increment the old value

2. The Better Counter

Naturally we want a mutable integer to avoid creating many integer objects. A mutable integer class can be defined as follows:

Class Mutableinteger {private int val;  Public Mutableinteger (int val) {this.val = val;}  public int Get () {return val;}  public void set (int val) {this.val = val;} Used to print value convinently public String toString () {return integer.tostring (val);}}

And the counter is improved and changed to the following:

hashmap<string, mutableinteger> newcounter = new hashmap<string, mutableinteger> (); for (String A:sarr) {if (Newcounter.containskey (a)) {Mutableinteger OldValue = Newcounter.get (a); Oldvalue.set (Oldvalu E.get () + 1); } else {Newcounter.put (A, new Mutableinteger (1));}}

This seems better because it does not require creating many Integer objects any longer. However, the search is still twice in each loop if a key exists.

3. The efficient Counter

The Hashmap.put (key, value) method returns the key ' s current value. This was useful, because we can use the reference of the old value to update the value without searching one more time!

hashmap<string, mutableinteger> efficientcounter = new hashmap<string, mutableinteger> (); for (String A:sarr) {Mutableinteger initvalue = new Mutableinteger (1);  Mutableinteger OldValue = Efficientcounter.put (A, initvalue); if (oldValue! = null) {Initvalue.set (Oldvalue.get () + 1);}}

4. Performance Difference

To test the performance of the three different approaches, the following code is used. The performance test is on 1 million times. The raw results is as follows:

Naive Approach:222796000better approach:117283000efficient approach:96374000

The difference is significant-223 vs. 117 vs. 96. There is huge difference between Naive and Better, which indicates this creating objects is expensive!

String s = "One, three, and three three"; string[] SArr = S.split ("");  long startTime = 0;long EndTime = 0;long Duration = 0; //naive approachstarttime = System.nanotime (); Hashmap<string, integer> counter = new hashmap<string, integer> (),  for (int i = 0; i < 1000000; i++) F or (String A:sarr) {if (Counter.containskey (a)) {int oldValue = Counter.get (a); Counter.put (A, oldValue + 1);} else { Counter.put (A, 1); }} endtime = System.nanotime ();d uration = Endtime-starttime; SYSTEM.OUT.PRINTLN ("Naive Approach:" + duration);  //Better approachstarttime = System.nanotime (); hashmap<string, mutableinteger> newcounter = new hashmap<string, mutableinteger> ();  for (int i = 0; I &lt ; 1000000; i++) for (String A:sarr) {if (Newcounter.containskey (a)) {Mutableinteger OldValue = Newcounter.get (a); Oldvalue.set (OL Dvalue.get () + 1); } else {Newcounter.put (A, new Mutableinteger (1));}}  endtime = System.nanotime ();d uration = endtiMe-starttime; SYSTEM.OUT.PRINTLN ("Better Approach:" + duration);  //Efficient approachstarttime = System.nanotime ();  hashmap<string, mutableinteger> efficientcounter = new hashmap<string, mutableinteger> ();  for (int i = 0; i < 1000000; i++) for (String A:sarr) {Mutableinteger initvalue = new Mutableinteger (1); Mutableinteger OldValue = Efficientcounter.put (A, InitValue);  if (oldValue! = null) {Initvalue.set (Oldvalue.get () + 1); }} endtime = System.nanotime ();d uration = Endtime-starttime; SYSTEM.OUT.PRINTLN ("Efficient Approach:" + duration);

When you use a counter, you probably also need a function to sort the map by value. You can check out the frequently used method of HashMap.

5. Solutions from Keith

Added a couple tests:
1) Refactored "better approach" to just call get instead of ContainsKey. Usually, the elements you want is in the HashMap so, reduces from both searches to one.
2) Added a test with Atomicinteger, which Michal mentioned.
3) Compared to singleton int array, which uses less memory according to http://amzn.com/0748614079

I ran the test program 3x and took the Min-to-remove variance from other programs. Note that your can ' t do this within the program or the results is affected too much, probably due to GC.

Naive:201716122better approach:112259166efficient approach:93066471better approach (without ContainsKey): 69578496Better approach (without ContainsKey, with Atomicinteger): 94313287Better approach (without containskey, with int []): 65877234

Better approach (without containskey):

hashmap<string, mutableinteger> efficientCounter2 = new hashmap<string, mutableinteger> (); for (int i = 0; I &l T Num_iterations;  i++) {for (String A:sarr) {Mutableinteger value = Efficientcounter2.get (a); if (value = null) {Value.set (Value.get () + 1);} else {efficientcounter2.put (A, new Mutableinteger (1));}}}

Better approach (without ContainsKey, with Atomicinteger):

hashmap<string, atomicinteger> atomiccounter = new hashmap<string, atomicinteger> (); for (int i = 0; i < NUM _iterations;  i++) {for (String A:sarr) {Atomicinteger value = Atomiccounter.get (a); if (value = null) {Value.incrementandget ();} else {atomiccounter.put (A, new Atomicinteger (1));}}}

Better approach (without ContainsKey, with int[]):

hashmap<string, int[]> intcounter = new hashmap<string, int[]> ();

for (int i = 0; i < num_iterations; i++)

{for (String A:sarr) {int[] Valuewrapper = Intcounter.get (a); if (Valuewrapper = = null) {Intcounter.put (A, new int[] {1});} else {valuewrapper[0]++;}}}

Guava ' s MultiSet is probably faster still.

6. Conclusion

The winner is the last one which uses int arrays.

Efficient Counter in Java

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.