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



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

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

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

mapping(address => bool) voter;

当涉及到气体消耗/费用时,在数组上循环并将其推送到映射是否被认为是最佳选择,或者如果函数接受一个地址并通过一些JavaScript功能从给定的UI进行迭代会更好?

选项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

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

最新更新