Skip to content

Instantly share code, notes, and snippets.

@vsmelov
Created March 1, 2021 15:52
Show Gist options
  • Save vsmelov/7f1b8b3eb50714998c66d49eafbce3c1 to your computer and use it in GitHub Desktop.
Save vsmelov/7f1b8b3eb50714998c66d49eafbce3c1 to your computer and use it in GitHub Desktop.
compare if/else implementation of swap over case/switch
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract SwapCheck {
function implementation1_0(uint256 x, uint256 y) public returns(uint256 xx, uint256 yy) {
// transaction cost: 22236 gas
// execution: 580 gas
assembly {
function foo1(x_, y_, reversed) -> a, b {
a := x_
b := y_
if reversed {
let tmp := b
b := a
a := tmp
}
}
x, y := foo1(x, y, 0)
xx, yy := foo1(x, y, 1)
}
}
function implementation2_0(uint256 x, uint256 y) public returns(uint256 xx, uint256 yy) {
// transaction cost: 22221 gas
// execution: 565 gas
assembly {
function foo2(x_, y_, reversed) -> a, b {
switch reversed
case 0 {
a := x_
b := y_
}
default {
a := y_
b := x_
}
}
x, y := foo2(x, y, 0)
xx, yy := foo2(x, y, 1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment