solidityのgas消費量調査
例えばバブルソート実行時、
storage領域(メンバ変数的なとこ)を直接何回も書き換えるより、
memory領域で計算終わらせて最後にstorage領域にコピーした方がgasが安いことがわかった。
https://ethfiddle.com/Ge47VLSHtf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
pragma solidity ^0.4.18; contract SimpleStore { uint[] ary; function swap(uint[] a, uint l, uint r) private pure { uint t = a[l]; a[l] = a[r]; a[r] = t; } function getBubbleSortedAry(uint[] a) public pure returns(uint[]) { uint len = a.length; uint i; uint j; for(i=0; i<len-1; i++){ for(j=i+1; j<len; j++){ if(a[j] < a[i]){ swap(a,i,j); } } } return a; } function test_getBubbleSortedAry() public view returns(uint[]){ return getBubbleSortedAry(ary); } function bubbleSortIndirect2() public { uint[] memory clone = getBubbleSortedAry(ary); for(uint i=0; i<ary.length; i++){ ary[i] = clone[i]; } } function bubbleSortIndirect() public { uint len = ary.length; uint i; uint j; uint[] memory clone = new uint[](len); for(i=0; i<len; i++){ clone[i] = ary[i]; } for(i=0; i<len-1; i++){ for(j=i+1; j<len; j++){ if(clone[j]<clone[i]){ swap(clone, i, j); } } } for(i=0; i<len; i++){ ary[i] = clone[i]; } } function bubbleSortDirect() public { uint len = ary.length; uint t; for(uint i=0; i<len-1; i++){ for(uint j=i+1; j<len; j++){ if(ary[j] < ary[i]){ t = ary[i]; ary[i] = ary[j]; ary[j] = t; } } } } function getArray() public view returns (uint[]){ return ary; } function setAryRandom5() public { uint length = 5; setAryReverse(length); } function setAryRandom8() public { uint length = 8; setAryReverse(length); } function setAryRandom10() public { uint length = 10; setAryReverse(length); } function setAryReverse(uint length) private { ary = new uint[](length); for(uint i=0; i<length; i++){ ary[i] = length-1-i; } } } |
gas消費量
functionsetAryRandom10からのbubbleSortIndirect2 : 524470
functionsetAryRandom10からのfunctionbubbleSortDirect : 101294