Unverified Commit 6d97f091 by rotcivegaf Committed by GitHub

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

* change implementation to save gas

* add average test with two max uni256 number
parent 1c1ebd76
...@@ -25,8 +25,8 @@ library Math { ...@@ -25,8 +25,8 @@ library Math {
* zero. * zero.
*/ */
function average(uint256 a, uint256 b) internal pure returns (uint256) { function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute. // (a + b) / 2 can overflow.
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); return (a & b) + (a ^ b) / 2;
} }
/** /**
......
...@@ -54,6 +54,11 @@ contract('Math', function (accounts) { ...@@ -54,6 +54,11 @@ contract('Math', function (accounts) {
const b = new BN('84346'); const b = new BN('84346');
expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); 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 () { describe('ceilDiv', function () {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment