LoginSignup
8
5

More than 5 years have passed since last update.

solidity の memory とか storageというkeywordが実際に何をしているのか

Last updated at Posted at 2018-02-14

公式ドキュメント

公式ドキュメントのFAQに書いてありました。


What is the memory keyword? What does it do?
The Ethereum Virtual Machine has three areas where it can store items.

The first is “storage”, where all the contract state variables reside. Every contract has its own storage and it is persistent between function calls and quite expensive to use.

The second is “memory”, this is used to hold temporary values. It is erased between (external) function calls and is cheaper to use.

The third one is the stack, which is used to hold small local variables. It is almost free to use, but can only hold a limited amount of values.

For almost all types, you cannot specify where they should be stored, because they are copied everytime they are used.

The types where the so-called storage location is important are structs and arrays. If you e.g. pass such variables in function calls, their data is not copied if it can stay in memory or stay in storage. This means that you can modify their content in the called function and these modifications will still be visible in the caller.

There are defaults for the storage location depending on which type of variable it concerns:

state variables are always in storage
function arguments are in memory by default
local variables of struct, array or mapping type reference storage by default
local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack


以下解説

Ethereum Virtual Machene (EVM) には3つのストレージ領域が存在します。

1. storage

storage領域は、全てのcontractに対して割り当てられた領域で、全ての状態変数はこの領域に保持されます。データは複数の関数呼び出しの間でも永続的に保持されますが、使用には非常にコスト(gas)がかかります。

2. memory

これは一時的な値を保持するストレージで、複数の関数呼び出し間で値は保持されませんが、コストはやや安くなります。

3. stack

stackはローカル変数をほぼ無料で保持できますが、使用量に制限があります。ローカル変数は基本スタックに保存されるが、structとarray,mappingはデフォルトでstorageを参照する。つまり、ローカル変数のstruct,array,mappingは関数の中で書き換えることができる。

struct,array,mapping以外の値は使われるたびにコピーされるため、ほぼ全ての型に関して、変数がどこに格納されているかを知ることはできない。

変数とストレージまとめ
- 状態変数はstorageに保存される
- 関数の引数はデフォルトでmemoryに保持される
- ローカル変数でも、struct,array,mappingはデフォルトでstorageを参照する。
- struct,array,mapping以外のローカル変数はstackに保持される。

こんな感じ。最近solidity楽しくなってきた。

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5