Add a function for shrinking memory arrays
See original GitHub issueš§ Motivation Solidity in-memory arrays canāt grow, because reallocation would be expensive and difficult to perform safely. But they can safely shrink.
Quite often a memory array needs to be passed around with a length
variable to simulate a dynamic data structure. In some cases itās only ever decreasing, e.g. when items are popped and consumed. This is both inefficient and dangerous, because Solidity only checks array.length
when sanity-checking accessed indexes, it doesnāt know about the other variable.
š Details
Add a function to library Arrays
:
function shrinkArray(uint256[] memory array, uint newLength) internal pure returns (uint256[] memory) {
require(newLength <= array.length, "Array: length after shrinking larger than before");
/// @solidity memory-safe-assembly
assembly {
mstore(array, newLength)
}
return array;
}
Edit:
I think that shrinkArray
is too verbose, just shrink
would be a better name, itād be called by Array.shrink(myArray, len);
or when using Array for uint256[]
, just by myArray.shrink(len)
.
Issue Analytics
- State:
- Created a year ago
- Comments:13 (13 by maintainers)
Iām concerned about the interaction with Solidity optimizations. I think that as long as the assembly block isnāt marked āmemory-safeā things should be fine, but there is some risk⦠See the recent compiler bug related to memory and assembly.
You are bechmarking a lot of extra stuff
With my compiler settings I get:
The basic iteration mload the length for every loop (and so does the popping) ⦠that cost a lot. The basic iteration does safe math on
i++
and bound checks onarray[i]
⦠that also cost a lot. there two account for more than half of the total cost.