数组作为映射变量的函数参数

Array as function parameter to mapping variable

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

function setVoters(address[] _inputAddresses) public ownerOnly {
    // [...]
}

使用上述函数的同一个合约有一个定义为映射的变量:

mapping(address => bool) voter;

循环遍历数组并将其推送到被认为是 gas 最佳选择的映射 consumption/expenses 或者如果函数接受一个地址并从给定的地址进行迭代会更好 UI 通过某些 JavaScript 功能?

选项 a:

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,你会付出更少。