Does anyone know how to efficiently concat two bytes arrays with assembly language to save gas costs? Currently I have
function mergeBytes(bytes param1, bytes param2) returns (bytes) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
Is there a way to avoid for
loops here?
Best Answer
Here's something I wrote for this purpose.
I'm new to ethereum programming, so there may be a mistake or some clear optimizations that can be made, but I tested this code in Remix. For 2 5 bytes arrays it costed about 1500 gas, with 2 larger (~ 40 bytes long) bytes arrays it costed about 1700 gas. It looks to be about a 100 gas increase per 32 bytes.
Please let me know if there are any clear optimizations as I'm using this in my own contract!
Edit: I made a change in the algorithm as it didn't work for byte arrays >32 bytes long.