-
Notifications
You must be signed in to change notification settings - Fork 2
김대영 Storage와 Memory 차이점
솔리디티에는 변수를 저장할 수 있는 Storage와 Memory 라는 공간이 존재한다. Storage는 블록체인 상에 영구적으로 저장되며, Memory는 임시적으로 저장되는 변수로 함수의 외부 호출이 일어날 때마다 초기화되어짐. (비유하자면 Storage는 하드 디스크, Memory는 RAM에 저장되는 것을 의미)
대부분의 경우에는 솔리디티가 알아서 메모리 영역을 구분해 준다, 상태 변수(함수 외부에 선언된 변수)는 storage로 선언되어 블록체인에 영구적으로 저장되는 반면, 함수 내에 선언된 변수는 memory로 선언되어 함수 호출이 종료되면 사라지게 됩니다.
contract SandwichFactory {
struct Sandwich {
string name;
string status;
}
Sandwich[] sandwiches;
function eatSandwich(uint _index) public {
// 솔리디티는 `storage`나 `memory`를 명시적으로 선언해야 한다는 경고를 출력합니다.
Sandwich mySandwich = sandwiches[_index];
}
mySandwich 구조체에 storage 선언을 추가하기
contract SandwichFactory {
struct Sandwich {
string name;
string status;
}
Sandwich[] sandwiches;
function eatSandwich(uint _index) public {
Sandwich storage mySandwich = sandwiches[_index];
}
contract SandwichFactory {
struct Sandwich {
string name;
string status;
}
Sandwich[] sandwiches;
function eatSandwich(uint _index) public {
Sandwich memory mySandwich = sandwiches[_index];
// 메모리 변수의 상태가 변해도 블록체인에는 영향을 미치지 않습니다.
mySandwich.status = "eaten";
}
int 와 string 앞에 저장타입 스마트 컨트랙트에서 선언한 변수들은 EVM내에 Storage에 어떻게 저장될까? EVM Storage에는 약 2의 256에 해당하는 메모리 슬롯이 존재한다. 이는 약 10의 77제곱에 해당한다고 한다. (우주를 구성하는 원자의 개수는 10의 80제곱에 해당한다.) Tip ! 슬롯의 갯수는 2²⁵⁶개이기때문에, uint256에서 허용하는 범위는 0 ~ 2²⁵⁶-1 까지 허용된다. 때문에 우리는 배열에 접근하는 코드에서 다음과 같은 안전장치를 해두어야 한다. 솔리디티 도큐먼트 슬롯 하나의 크기는 256 비트 = 32 바이트 이다. EVM Stack — 256비트 크기의 1024개의 스택으로 이루어져 있다 EVM Memory — 함수를 호출하거나 메모리 연산을 수행할 때 임시로 사용된다. 이더리움에서 메시지 호출이 발생할 때마다, 깨끗하게 초기화된 메모리 영역이 컨트랙트에 제공된다. EVM Call Data — 트랜잭션을 요청했을때, 전송되는 데이터 들이 기록된다.
-
Stroage 랑 memory 가스 비용 https://dlt-repo.net/storage-vs-memory-vs-stack-in-solidity-ethereum/
-
EVM 3가지 영역, 4가지 기본 조건 https://stackoverflow.com/questions/33839154/in-ethereum-solidity-what-is-the-purpose-of-the-memory-keyword
기본 자료형이 아닌 것은 저장소를 명시해 주어야하는데string을 사용하는 부분에 memory타입으로 명시한다.
기본형 uint/int ; uint, int는 뒤에 256이 생략되어 있다. (u는 unsigned 의미) uint8~uint256 ; 여기서 숫자는 비트수를 의미. 1바이트부터 32바이트까지 있다. bool : true or false byte : uint8과 같다고 생각하면 된다. address : 20바이트 주소값 address payable : address타입인데 멤버함수가 있다. transfer, send. address payable x = address(uint160(to));