From 5b2dc71a35a67a0f52316629e36424c895d9f777 Mon Sep 17 00:00:00 2001 From: John Vasileff Date: Thu, 13 Aug 2015 15:28:44 -0400 Subject: [PATCH] optimize sum() for Integers and Floats This implementation avoids using a boxed type for the `sum` accumulator variable when summing Integers and Floats. --- src/ceylon/language/sum.ceylon | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/ceylon/language/sum.ceylon b/src/ceylon/language/sum.ceylon index 7abcbc3cf..ebe47e89d 100644 --- a/src/ceylon/language/sum.ceylon +++ b/src/ceylon/language/sum.ceylon @@ -4,10 +4,33 @@ see (`function product`) shared Value sum({Value+} values) given Value satisfies Summable { value it = values.iterator(); - assert (!is Finished first = it.next()); - variable value sum = first; - while (!is Finished val = it.next()) { - sum += val; + value first = it.next(); + if (is Integer first) { + // unbox; don't infer type Value&Integer + variable Integer sum = first; + while (is Integer val = it.next()) { + Integer unboxed = val; + sum += unboxed; + } + assert (is Value result = sum); + return result; + } + else if (is Float first) { + // unbox; don't infer type Value&Float + variable Float sum = first; + while (is Float val = it.next()) { + Float unboxed = val; + sum += unboxed; + } + assert (is Value result = sum); + return result; + } + else { + assert (!is Finished first); + variable value sum = first; + while (!is Finished val = it.next()) { + sum += val; + } + return sum; } - return sum; }