From ee408ad785eb94f1f416d53f50de3d14a974dbce Mon Sep 17 00:00:00 2001 From: Dan Liu Date: Sat, 26 Mar 2022 10:27:07 +0800 Subject: [PATCH] perf: simplify function removeStorage --- contracts/lib/AddressArrayUtils.sol | 11 ++++++----- contracts/lib/StringArrayUtils.sol | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/contracts/lib/AddressArrayUtils.sol b/contracts/lib/AddressArrayUtils.sol index 5fb87a261..b17e5d39d 100644 --- a/contracts/lib/AddressArrayUtils.sol +++ b/contracts/lib/AddressArrayUtils.sol @@ -103,12 +103,13 @@ library AddressArrayUtils { internal { (uint256 index, bool isIn) = indexOf(A, a); - if (!isIn) { - revert("Address not in array."); - } else { - uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here - if (index != lastIndex) { A[index] = A[lastIndex]; } + + if (isIn) { // address a is in array A, so array A is not emtpy, and A.length >= 1 + uint256 lastIndex = A.length - 1; + A[index] = A[lastIndex]; // for save gas, we not check: index != lastIndex A.pop(); + } else { + revert("Address not in array."); } } diff --git a/contracts/lib/StringArrayUtils.sol b/contracts/lib/StringArrayUtils.sol index 9ac97f96f..ea69cbaf0 100644 --- a/contracts/lib/StringArrayUtils.sol +++ b/contracts/lib/StringArrayUtils.sol @@ -50,12 +50,13 @@ library StringArrayUtils { internal { (uint256 index, bool isIn) = indexOf(A, a); - if (!isIn) { - revert("String not in array."); - } else { - uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here - if (index != lastIndex) { A[index] = A[lastIndex]; } + + if (isIn) { // string a is in the array A, so array A is not empty, and A.length >= 1 + uint256 lastIndex = A.length - 1; + A[index] = A[lastIndex]; // to save gas, we not check: index != lastIndex A.pop(); + } else { + revert("String not in array."); } } }