본문 바로가기

study/BlockChain

컨트랙 최적화

728x90

빅오 표기법*보다 가스문제가 더 중요하다...

옵코드에 따라 가스가 좌지우지되기때문이다.

 

스마트컨트랙 디자인시에는 가스비용을 어떻게하면 줄일 수 있을지 고민해야한다.

 

1. 컨트랙 배포할 때의 비용

- 주석, 변수이름, 타입이름은 가스 소모 없음. 

- 불필요한 코드 정리

   ex)

function useless(uint a) public {
	if(a> 10){
    	if(a+a <10) {
        	b=20; //이 라인에 올 수가 없음
        }
    }
}

 

2. 컨트랙 내의 함수를 불러올때의 비용

- pure, view 붙은 함수는 비용 안들지만, 그 외의 것은 비용이...

 

ex1) 비싼 연산을 최대한 줄이기

uint total= 0;
function expensive () public {
	for (uint i=0; i<10; i++)
    	total +=2;
}

 상태변수 total은 저장위치가 storage인데, 옵코드에서 보면 연산비용이 비싼 곳. 

 업데이트 할때마다 가스비용이 들게 된다.

uint total =0;
function optimized () public{
	uint temp= 0;
	for (uint i=0; i<10; i++)
    	total+= 2;
    total += temp;
}

로컬변수를 안에다 선언하고, for를  돌릴때 증가하는 것을 로컬변수가 담당하도록 한다.

마지막에 total상태변수에 temp 로컬변수를 대입해서 한번에 끝! 

-> 가스비용을 엄청 아낀 케이스.

 

ex2) 반복문 관련된 패턴

function expensive() public{
	uint a=0;
    uint b=0;
    for (uint i=0; i<10; i++)
    a +=2;
    for (uint j=0; j<10; j++)
    b+= 4;
}

for를 한번으로 끝낼 수 있는 상황.

function optimized() public{
	uint a=0;
    uint b=0;
    for (uint i=0; i<10; i++){
    	a +=2;
    	b+= 4;
}

이렇게 한번만 사용해서 효율성 up

 

ex3) 고정된 크기 bytes 배열 쓰기

string stringText = "hello world";
bytes32 bytes32Text ="hello world";

function bytes32overstring() public{
	stringText= "my world";
    bytes32Text= "my world";
}

이더리움 가상머신은 32bytes문자에 최적화되어있다. 

 

요약!

- 불필요한 코드 정리

- 비싼 연산 최대한 줄이기(상태변수)

- 반복문 패턴 제대로 쓰기

- string 대신 bytes32 쓰기

 

배열 사용시 주의점

- 무제한 크기의 배열 반복 피해야함

   반복해야할 데이터가 많아서 가스한도까지 도달하면, 데이터 처리를 하다가 끝내지못하고 셧다운될 수 있음.

   반복문은 길이 50이하의 배열을 돌릴때 효율적이라고 한다.

   50이 넘는다면? -> 매핑을 사용한다.

struct Student{
	uint studentId;
    string name;
}

Student[] students;

function updateStudentById(uint _studentId, string _name) public{
	for (uint i=0; i< students.length; i++){
    	if( students[i].studentId == _studentId){
        	students[i].name = _name;
        }
    }
}
struct Student{
	uint studentId;
    string name;
}

mapping(uint => Student) studentInfo;

function updateStudentById(uint _studentId, string _name) public{
	Student storage student= studentInfo[_studentId];
    student.name= _name;
}

 

728x90
반응형

'study > BlockChain' 카테고리의 다른 글

부동산 dapp 미리보기 및 주의점  (2) 2019.10.13
가스란?  (4) 2019.10.12
값 타입  (2) 2019.10.05
함수 타입 제어자  (2) 2019.10.05
접근 제어자  (2) 2019.10.05