首页 > 解决方案 > 数组作为映射变量的函数参数

问题描述

假设一个函数接受一个地址数组,如下所示:

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

标签: ethereumsoliditysmartcontracts

解决方案


在 gas 效率方面最好的是选项 a,调用一个函数需要相当多的 gas,所以如果你在一个大的 tx 中而不是在许多小的 tx 中完成这一切,你会花更少的钱。


推荐阅读