ethereum - 数组作为映射变量的函数参数
问题描述
假设一个函数接受一个地址数组,如下所示:
function setVoters(address[] _inputAddresses) public ownerOnly {
// [...]
}
使用上述函数的同一合约有一个定义为映射的变量:
mapping(address => bool) voter;
当涉及到气体消耗/费用时,循环遍历数组并将其推送到映射是否被认为是最佳选择,或者如果函数接受一个地址并通过某些 JavaScript 功能从给定 UI 进行迭代会更好?
选项一:
function setVoters(address[] _inputAddresses) public ownerOnly {
// [...]
for (uint index = 0; index < _inputAddresses.length; index++) {
voter[_inputAddresses[index]] = true;
}
}
对比
选项 b:
function setVoter(address _inputAddress) public ownerOnly {
// [...]
voter[_inputAddress] = true;
}
JavaScript 看起来像这样
// loop condition starts here
await task.methods.setVoter(address[key]).send({
from: accounts[0]
});
// loop condition ends here
解决方案
在 gas 效率方面最好的是选项 a,调用一个函数需要相当多的 gas,所以如果你在一个大的 tx 中而不是在许多小的 tx 中完成这一切,你会花更少的钱。
推荐阅读
- android - FrameLayout 项目视图在切换其可见性后丢失 z-index
- function - twilio studio contact.channel.address 给出奇怪的字符串
- c# - 对非十进制货币使用双精度类型?
- reporting-services - 如何使用显示的参数面板链接到其他报告?
- c++ - 分配不同类型的指针
- c++ - 如何将 const 引用分配给非 const 变量?
- html - 如何按名称选择复选框
- linux - 如何使用“system()”终止在 perl 脚本中启动的命令
- css - 为 Formik Multi-Select 组件设置样式,使其看起来像 Material-UI 选择
- c# - 在 ASP.NET Core Web API 中处理脏数据的最佳方法