From 2d8adbf5148543bebc026d984f54cc43b9e9f545 Mon Sep 17 00:00:00 2001 From: Gilles Sadowski Date: Sat, 11 Apr 2020 13:42:03 +0200 Subject: [PATCH] Avoid performance degradation of indexed access when using a linked list. Thanks to Artavazd Balaian. Closes #134. --- .../commons/math4/distribution/EnumeratedDistribution.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java b/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java index 5b1cd302d..27f53bde4 100644 --- a/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java +++ b/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java @@ -86,9 +86,8 @@ public class EnumeratedDistribution implements Serializable { NotANumberException { singletons = new ArrayList<>(pmf.size()); final double[] probs = new double[pmf.size()]; - - for (int i = 0; i < pmf.size(); i++) { - final Pair sample = pmf.get(i); + int count = 0; + for (Pair sample : pmf) { singletons.add(sample.getKey()); final double p = sample.getValue(); if (p < 0) { @@ -100,7 +99,7 @@ public class EnumeratedDistribution implements Serializable { if (Double.isNaN(p)) { throw new NotANumberException(); } - probs[i] = p; + probs[count++] = p; } probabilities = MathArrays.normalizeArray(probs, 1.0);