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

  • 相关阅读:
    5大用例设计笔试大题,附详细解析!
    面试被问到:fiddler 在工作中有哪些应用?怎么破?
    Jmeter设置中文
    Git 操作
    测压数据处理脚本
    python通过126邮箱发送邮件
    Python读取Mysql数据并写入Excel
    Git基本操作命令
    python接口自动化框架探讨
    寒假每日一题(B
  • 原文地址:https://www.cnblogs.com/baizx/p/9249722.html
Copyright © 2011-2022 走看看