This is an automated email from the ASF dual-hosted git repository.

sunlan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/master by this push:
     new 296b766  GROOVY-8945: Improve performance of DGM `groupBy` and 
`countBy`(closes #849)
296b766 is described below

commit 296b7666557898cd625a3e38ea82f6fdf264fedc
Author: Daniel Sun <sun...@apache.org>
AuthorDate: Sat Jan 5 21:50:34 2019 +0800

    GROOVY-8945: Improve performance of DGM `groupBy` and `countBy`(closes #849)
---
 .../codehaus/groovy/runtime/DefaultGroovyMethods.java | 19 +++++++++++--------
 src/test/groovy/GroovyMethodsTest.groovy              |  7 +++++++
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git 
a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java 
b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index f2a6b26..db43fd2 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -5883,20 +5883,23 @@ public class DefaultGroovyMethods extends 
DefaultGroovyMethodsSupport {
      * @since 1.5.0
      */
     protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T 
element, K value) {
-        if (answer.containsKey(value)) {
-            answer.get(value).add(element);
-        } else {
-            List<T> groupedElements = new ArrayList<T>();
-            groupedElements.add(element);
+        List<T> groupedElements = answer.get(value);
+
+        if (null == groupedElements) {
+            groupedElements = new ArrayList<T>();
             answer.put(value, groupedElements);
         }
+
+        groupedElements.add(element);
     }
 
     private static <T> void countAnswer(final Map<T, Integer> answer, T 
mappedKey) {
-        if (!answer.containsKey(mappedKey)) {
-            answer.put(mappedKey, 0);
+        Integer current = answer.get(mappedKey);
+
+        if (null == current) {
+            current = 0;
         }
-        int current = answer.get(mappedKey);
+
         answer.put(mappedKey, current + 1);
     }
 
diff --git a/src/test/groovy/GroovyMethodsTest.groovy 
b/src/test/groovy/GroovyMethodsTest.groovy
index b23fd27..dd31077 100644
--- a/src/test/groovy/GroovyMethodsTest.groovy
+++ b/src/test/groovy/GroovyMethodsTest.groovy
@@ -786,6 +786,13 @@ class GroovyMethodsTest extends GroovyTestCase {
         assert result2['cc']['cd']['ce'] == [cc: 33]
     }
 
+    void testCountBy() {
+        def list = ['a', 'b', 'c', 'a']
+        def result = list.countBy { it }
+
+        assert [a: 2, b: 1, c: 1] == result
+    }
+
     def leftCol = ["2"]
     def rightCol = ["1", "2", "3"]
 

Reply via email to