zoukankan      html  css  js  c++  java
  • solidity_mapping_implementation

    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 吧.

  • 相关阅读:
    CLRS 10.28
    [转]教你如何查看各种浏览器的Cookies[IE cookies信息]
    红黑树c实现
    ubuntu下eclipse中键盘失灵
    putty中文乱码解决
    [ 转]关于linux下wireshark启动时Lua报错
    c/c++运算符优先级
    CLRS 10.45
    ubuntu 12.04 安装NS2
    SQL IsDate()
  • 原文地址:https://www.cnblogs.com/baizx/p/9249722.html
Copyright © 2011-2022 走看看