Groovy collections performance considerations regarding space/time

前端 未结 1 1780
感动是毒
感动是毒 2020-12-02 00:05

What is the performance of Groovys collection methods (regarding space(!) and time) in comparison to plain Java for-loops?

Eg for this use cases:

  • sum()
相关标签:
1条回答
  • 2020-12-02 00:50

    Interesting benchmark. No surprise that sum() is slower. Here's how implementation looks like:

    private static Object sum(Iterable self, Object initialValue, boolean first) {
            Object result = initialValue;
            Object[] param = new Object[1];
            for (Object next : self) {
                param[0] = next;
                if (first) {
                    result = param[0];
                    first = false;
                    continue;
                }
                MetaClass metaClass = InvokerHelper.getMetaClass(result);
                result = metaClass.invokeMethod(result, "plus", param);
            }
            return result;
    }
    

    As You can see it must be generic and uses meta programming. The result is bigger time cost.

    The results of the benchmark You pasted are clear and pretty self descriptive. If You really need better performance it seems that better idea is to use for loops.

    0 讨论(0)
提交回复
热议问题