📜 [專欄新文章] Solidity Weekly #9
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
什麼時候用 storage,什麼時候該用 memory?
其實這副標題,有可能又會誤導大家如何寫 solidity。簡單講它們是完全不一樣的東西。所以應該會用在不同的地方,做不同的事才對。
先簡單說明它們的原理:
storage 就是 smart contract 正常存放狀態 (state) 的地方,而這些地方就是用來呈現在區塊鏈裡狀態值的變更。所以一般來說,全域變數就會用 storage 來儲存。
它以 32 bytes 為單位類似 hash 的方式做 key/value 的查詢。所以即時key 1 跟 key 1000,所用的空間跟 key 1 跟 key 2 一樣。(所花的 gas 也應該相同)
另外,通常方程式帶入的變數或回傳值,會以 memory 方式表示,或有些 compiler 會用 stack 來儲存 (不花 gas)。若帶入變數內容來自於一個全域變數,它會複製一份 storage 裡的資料到 memory 做修改。但如果你在方程式帶入的變數前用 storage 保留字來描述,它就變成 passed by reference,把 storage 的位置直接傳給該方程式,因此所有的變動,都會直接改到 storage 裡的值。
而一般在方程式裡的本域變數 (local variables),也預設用 storage 來處理,除非你故意用 memory 保留字來定義它。但用 memory 來處理陣列會有點困難。不像 storage 的陣列,可以用 push。(如下錯誤範例)
function createRoom() public{ address[] memory adr; adr.push(msg.sender); // compiler error ...}
但為了節省 gas 的消耗,在方程式裡本域變數改用 memory 也是很常見的事。
links 分享;
Ethereum Solidity: Memory vs Storage & How to initialize an array inside a struct — (Georgios Konstantopoulos)
Solidity Introduction — (A very good Solidity tutorial from BitDegree)
New Features of Solidity 0.5.0 — (@Christian Reitwiessner)
Solidity Weekly #9 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
「new struct array」的推薦目錄:
- 關於new struct array 在 Taipei Ethereum Meetup Facebook 的最佳解答
- 關於new struct array 在 Create an array of structure using new - c++ - Stack Overflow 的評價
- 關於new struct array 在 C array of structs - YouTube 的評價
- 關於new struct array 在 10 - How to Create an Array of Structs and a Struct Containing ... 的評價
- 關於new struct array 在 Dynamically Allocate An Array Of Structs - YouTube 的評價
- 關於new struct array 在 How to create an array of struct? - Ethereum Stack Exchange 的評價
- 關於new struct array 在 A Struct which contains Array of Structs can't be initialized #4115 的評價
new struct array 在 C array of structs - YouTube 的推薦與評價
C array of structs tutorial example explained#C # struct # array. ... <看更多>
new struct array 在 10 - How to Create an Array of Structs and a Struct Containing ... 的推薦與評價
0:00 · New ! Watch ads now so you can enjoy fewer interruptions. Got it ... ... <看更多>
new struct array 在 Create an array of structure using new - c++ - Stack Overflow 的推薦與評價
... <看更多>