结构体状态变量两种初始化Data public _data0 = Data(123, 456, true);Data public _data1 = Data({ tokenId: 123, price: 456, state: true});Gas消耗对比// SPDX-License-Identifier: GPL-3.0pragma solidity >=0.7.0 <0.9.0;contract TestStruct { struct Data {
结构体
状态变量两种初始化
Data public _data0 = Data(123, 456, true);Data public _data1 = Data({tokenId: 123, price: 456, state: true});
Gas消耗对比
// SPDX-License-Identifier: GPL-3.0pragma solidity >=0.7.0 <0.9.0;contract TestStruct { struct Data { uint256 tokenId; uint256 price; bool state; } mapping(uint256 => Data) public Datas; Data public _data0 = Data(123, 456, true); Data public _data1 = Data({tokenId: 123, price: 456, state: true}); constructor() {} //88227 gas function SetData0(uint256 tokenId) external { Datas[tokenId] = Data(tokenId, 123, true); } //88114 gas function SetData1(uint256 tokenId) external { Data storage data = Datas[tokenId]; data.tokenId = tokenId; data.price = 123; data.state = true; } //88301 gas function SetData2(uint256 tokenId) external { Datas[tokenId].tokenId = tokenId; Datas[tokenId].price = 123; Datas[tokenId].state = true; }}
SetData1 | 88114 gas |
---|---|
SetData0 | 88227 gas |
SetData2 | 88301 gas |
建议
先声明storage变量,接收状态变量。
Data storage data = Datas[tokenId];data.tokenId = tokenId;
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。