From 81e1bf5d23430f7c344ed5f89212403dd722a4ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Venturo?= Date: Fri, 24 Jan 2020 12:36:59 -0300 Subject: [PATCH] Add optimization for removal of last slot --- contracts/utils/EnumerableSet.sol | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/contracts/utils/EnumerableSet.sol b/contracts/utils/EnumerableSet.sol index 7b4b586ec..9d2f6f68b 100644 --- a/contracts/utils/EnumerableSet.sol +++ b/contracts/utils/EnumerableSet.sol @@ -66,12 +66,15 @@ library EnumerableSet { uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; - address lastValue = set.values[lastIndex]; + // If the element we're deleting is the last one, we can just remove it without doing a swap + if (lastIndex != toDeleteIndex) { + address lastValue = set.values[lastIndex]; - // Move the last value to the index where the deleted value is - set.values[toDeleteIndex] = lastValue; - // Update the index for the moved value - set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based + // Move the last value to the index where the deleted value is + set.values[toDeleteIndex] = lastValue; + // Update the index for the moved value + set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based + } // Delete the index entry for the deleted value delete set.index[value];