solidity 学习笔记(7)内联汇编
为什么要有内联汇编?
//普通循环和内敛汇编循环比较
pragma solidity ^0.4.25;
contract Assembly{
function nativeLoop() public view returns(uint _r){
for(uint i=0;i<10;i++){
_r = _r +i;
}
}
function asmLoop() public view returns (uint _r){
assembly{
let i:=0
loop:
i:=add(i,1)
_r:=add(_r,i)
jumpi(loop,lt(i,9))
}
}
}
官网:https://solidity.readthedocs.io/en/develop/assembly.html
函数式操作码:mul(1, add(2, 3)) 替代 push1 3 push1 2 add push1 1 mul
汇编局部变量:let x := add(2, 3) let y := mload(0x40) x := add(x, y)
访问外部变量:function f(uint x) { assembly { x := sub(x, 1) } }
标签:let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0))
循环:for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) }
switch语句:switch x case 0 { y := mul(x, 2) } default { y := 0 }
函数调用:function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } }