Skip to content

Commit

Permalink
Gas optimization on average function of Math.sol (OpenZeppelin#2757)
Browse files Browse the repository at this point in the history
* change implementation to save gas

* add average test with two max uni256 number
  • Loading branch information
rotcivegaf authored Jul 10, 2021
1 parent 1c1ebd7 commit 6d97f09
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 2 additions & 2 deletions contracts/utils/math/Math.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions test/utils/math/Math.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit 6d97f09

Please sign in to comment.