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

目录
相关文章
|
18天前
|
JavaScript
TypeScript工具类 Partial 和 Required 的详细讲解
TypeScript工具类 Partial 和 Required 的详细讲解
|
Java Maven
Maven - Error:java: Annotation processing is not supported for module cycles. Please ensure that all
Maven - Error:java: Annotation processing is not supported for module cycles. Please ensure that all
792 0
Maven - Error:java: Annotation processing is not supported for module cycles. Please ensure that all
|
8月前
|
数据建模 数据库
什么是 SAP CDS view 中的 Exposed Association with filter 技术
什么是 SAP CDS view 中的 Exposed Association with filter 技术
35 0
|
前端开发 编译器 区块链
聊聊Solidity中的constant修饰符
聊聊Solidity中的constant修饰符
208 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
76 0
filter operation implementation in Gateway framework
UI5 control inheritance implementation question
UI5 control inheritance implementation question
UI5 control inheritance implementation question
filter operation implementation in SAP Gateway framework
Created by Wang, Jerry, last modified on Dec 30, 2015
filter operation implementation in SAP Gateway framework
SAP UI5 extension component loads standard component
# Created by Wang, Jerry, last modified on May 20, 2015
102 0
SAP UI5 extension component loads standard component
ABAP里的OAuth2.0 Standard Package
Sent: Wednesday, December 26, 2012 6:53 PM
124 0
ABAP里的OAuth2.0 Standard Package
implementation of CreateBindingContext
Created by Jerry Wang, last modified on Jul 29, 2015
120 0
implementation of CreateBindingContext

热门文章

最新文章