[英]How to optimize this smart contract function in Solidity about deleting an element in particular index of an array
我使用以下庫代碼根據其索引刪除數組中的元素。 在我看來,唯一的方法是使用循環,但它會消耗大量氣體。 還有其他優化代碼可以解決這個問題嗎?
library ArrayLibrary {
function remove(uint[] storage _arr, uint _removedIndex) public returns(uint[] memory){
require(_arr.length > 0, "No element in Array.");
for(uint i; i < _arr.length - 1; i++){
if (i >= _removedIndex) {
_arr[i] = _arr[i + 1];
}
}
_arr.pop();
return _arr;
}
}
contract TestLibrary {
uint[] arr;
using ArrayLibrary for uint[];
function deleteArrEle(uint[] calldata _arr, uint deletedIndex) public returns (uint[] memory deletedArr) {
arr = _arr;
deletedArr = arr.remove(deletedIndex);
}
}
如果您不介意調換項目的順序,您可以將最后一項復制到不需要的項目的 position,然后刪除最后一項。
function remove(uint[] storage _arr, uint _removedIndex) public returns(uint[] memory){
require(_arr.length > 0, "No element in Array.");
_arr[_removedIndex] = _arr[_arr.length-1];
_arr.pop();
return _arr;
}
輸入數組[1,2,3,4]
,從索引 1(值 2)處刪除。 Output [1,4,3]
。
鏈接排序列表還有一些更復雜的解決方法。 例如,Liquity 協議的SortedTroves中的示例代碼。
排序后的數據不存儲在數組中,而是存儲在指向上一個和下一個項目的結構映射中。
該合同還包含有關最低和最高價值的密鑰的信息。
當您刪除一個項目時,您只會刪除這個特定項目,並更改最初指向該項目的 2 個鏈接(下一個和上一個)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.