소스 검색

Gas optimization on average function of Math.sol (#2757)

* change implementation to save gas

* add average test with two max uni256 number
rotcivegaf 4 년 전
부모
커밋
6d97f09195
2개의 변경된 파일7개의 추가작업 그리고 2개의 파일을 삭제
  1. 2 2
      contracts/utils/math/Math.sol
  2. 5 0
      test/utils/math/Math.test.js

+ 2 - 2
contracts/utils/math/Math.sol

@@ -25,8 +25,8 @@ library Math {
      * zero.
      */
     function average(uint256 a, uint256 b) internal pure returns (uint256) {
-        // (a + b) / 2 can overflow, so we distribute.
-        return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
+        // (a + b) / 2 can overflow.
+        return (a & b) + (a ^ b) / 2;
     }
 
     /**

+ 5 - 0
test/utils/math/Math.test.js

@@ -54,6 +54,11 @@ contract('Math', function (accounts) {
       const b = new BN('84346');
       expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b));
     });
+
+    it('is correctly calculated with two max uint256 numbers', async function () {
+      const a = MAX_UINT256;
+      expect(await this.math.average(a, a)).to.be.bignumber.equal(bnAverage(a, a));
+    });
   });
 
   describe('ceilDiv', function () {