Solidity区块链-内存、存储和映射解释简要说明



请有人用例子向我解释一下映射、存储和内存的问题?我不清楚一些文章

谢谢!!

存储和内存

Solidity中的存储和内存关键字类似于计算机的硬盘和RAM。与RAM非常相似,Solidity中的Memory是存储数据的临时位置,而Storage在函数调用之间保存数据。Solidity智能合约在执行过程中可以使用任何数量的内存,但一旦执行停止,下次执行时内存将被完全擦除。另一方面,存储是持久的,每次执行智能合约都可以访问以前存储在存储区域上的数据

以太坊虚拟机上的每一笔交易都会花费我们一些天然气。燃气消耗量越低,Solidity代码就越好。与存储的气体消耗相比,内存的气体消耗不是很显著。因此,最好使用Memory进行中间计算,并将最终结果存储在Storage中。

  1. 结构的状态变量和局部变量,数组总是默认情况下存储在存储器中
  2. 函数参数在内存中
  3. 每当使用关键字创建数组的新实例时"memory",则会创建该变量的新副本
  4. 更改新实例的数组值不会影响原始数组

示例#1:在下面的示例中,创建了一个合同来演示"storage"关键字。

pragma solidity ^0.4.17;

// Creating a contract
contract helloGeeks
{
// Initialising array numbers
int[] public numbers;

// Function to insert values
// in the array numbers
function Numbers() public
{
numbers.push(1);
numbers.push(2);

//Creating a new instance
int[] storage myArray = numbers;

// Adding value to the
// first index of the new Instance
myArray[0] = 0;
} 
}

输出:

当我们在上面的代码中检索数组编号的值时,请注意,数组的输出是[0,2],而不是[1,2]。


示例#2:在下面的示例中,创建了一个契约来演示关键字"内存"。

pragma solidity ^0.4.17;

// Creating a contract
contract helloGeeks
{ 
// Initialising array numbers
int[] public numbers;

// Function to insert
// values in the array
// numbers
function Numbers() public
{
numbers.push(1);
numbers.push(2);

//creating a new instance
int[] memory myArray = numbers;

// Adding value to the first
// index of the array myArray
myArray[0] = 0;
} 
}

输出:

当我们在上面的代码中检索数组编号的值时,请注意数组的输出是[1,2]。在这种情况下,更改myArray的值不会影响数组编号中的值,这是因为函数停止了,数组没有保存


映射

映射是完全不同的东西。这些用于以键值对的形式存储数据,键可以是任何内置的数据类型,但不允许使用引用类型,而值可以是任何类型。映射主要(但不限于(用于将唯一的以太坊地址与关联的值类型相关联。映射与数组非常相似

mapping(key => value) <name>;

示例#1:

实用主义稳固性^0.4.17;

// Creating a contract
contract helloGeeks
{ 
// Initialising mapping of user balance
mapping(address => uint) balance;

// Function to insert user balance

function Insert(address _user, uint _amount) public
{
//insert the amount to a specific user
balance[_user] = _amount
} 
//function to view the balance
function View(address _user) public view returns(uint)
{
//see the value inside the mapping, it will return the balance of _user
return balance[_user];
} 
}

最新更新