solidity_mapping_implementation

简介: solidity 中 mapping 是如何存储的为了探测 solidity mapping 如何实现,我构造了一个简单的合约. 先说结论,实际上 mapping的访问成本并不比直接访问storage变量多花费更多的 gas.

solidity 中 mapping 是如何存储的

为了探测 solidity mapping 如何实现,我构造了一个简单的合约. 先说结论,实际上 mapping的访问成本并不比直接访问storage变量多花费更多的 gas.两者几乎差不多.

构造合约

pragma solidity ^0.4.23;

contract TestMap{
     mapping(uint256 => uint256) public channels;
     function TestSet() external{
        channels[0x39]=0x77;
     }
}

合约非常简单,就是写一个 mapping.

汇编指令

最主要是这些指令里面就有一条昂贵的就是 sstore, 至少需要5000gas.

    /* "testmapping.sol":151:155  0x77 */
      0x77
        /* "testmapping.sol":136:144  channels */
      0x0
        /* "testmapping.sol":136:150  channels[0x39] */
      dup1
        /* "testmapping.sol":145:149  0x39 */
      0x39
        /* "testmapping.sol":136:150  channels[0x39] */
      dup2
      mstore
      0x20
      add
      swap1
      dup2
      mstore
      0x20
      add
      0x0
      keccak256
        /* "testmapping.sol":136:155  channels[0x39]=0x77 */
      dup2
      swap1
      sstore
      pop

总结

由于指令的成本较低,写 storage 最少需要5000gas, 而 sha3只需要30+gas, 可以忽略不计,其他指令也很便宜.
当然如果是读的话,就稍微贵一点点,读 storage 是200gas, 那么 sha3加上这些指令,估计就有接近100了.
不过如果mapping 确实可以带来便利,那就用 mapping 吧.

目录
相关文章
|
API
Gradle中implementation和api的区别
api关键字与旧的compile关键字完全相同。因此,如果用api替换了所有的compile,是完全ok的
316 0
filter operation implementation in Gateway framework
Created by Wang, Jerry, last modified on Dec 28, 2015 data type is singleton field type and actual value must be compatible
filter operation implementation in Gateway framework
UI5 control inheritance implementation question
UI5 control inheritance implementation question
UI5 control inheritance implementation question
|
XML 数据格式
SAP Fiori Elements - How complex binding defined in XML view is parsed
SAP Fiori Elements - How complex binding defined in XML view is parsed
SAP Fiori Elements - How complex binding defined in XML view is parsed
filter operation implementation in SAP Gateway framework
Created by Wang, Jerry, last modified on Dec 30, 2015
104 0
filter operation implementation in SAP Gateway framework
implementation of CreateBindingContext
Created by Jerry Wang, last modified on Jul 29, 2015
128 0
implementation of CreateBindingContext
SAP UI5 extension component loads standard component
# Created by Wang, Jerry, last modified on May 20, 2015
109 0
SAP UI5 extension component loads standard component
How to create ABAP implicit enhancement implementation
How to create ABAP implicit enhancement implementation
127 0
How to create ABAP implicit enhancement implementation
ABAP Text table implementation
Created by Wang, Jerry, last modified on Dec 20, 2014
ABAP Text table implementation