📜 [專欄新文章] 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.
👏 歡迎轉載分享鼓掌
同時也有10000部Youtube影片,追蹤數超過2,910的網紅コバにゃんチャンネル,也在其Youtube影片中提到,...
「struct array initialize」的推薦目錄:
- 關於struct array initialize 在 Taipei Ethereum Meetup Facebook 的精選貼文
- 關於struct array initialize 在 コバにゃんチャンネル Youtube 的最佳貼文
- 關於struct array initialize 在 大象中醫 Youtube 的最佳解答
- 關於struct array initialize 在 大象中醫 Youtube 的最佳解答
- 關於struct array initialize 在 Initializing array of structures [duplicate] - Stack Overflow 的評價
- 關於struct array initialize 在 Initializing Array of structs - Arduino Stack Exchange 的評價
- 關於struct array initialize 在 C array of structs - YouTube 的評價
- 關於struct array initialize 在 Syntax for array default initialization #4847 - ziglang/zig - GitHub 的評價
- 關於struct array initialize 在 STRUCTURES IN C | DEFINE,INITIALIZE WITH EXAMPLE 的評價
struct array initialize 在 Initializing Array of structs - Arduino Stack Exchange 的推薦與評價
Here you are defining an array. Since it is in global scope, and not explicitly initialized, it is implicitly initialized to all bytes zero. ... <看更多>
相關內容
struct array initialize 在 C array of structs - YouTube 的推薦與評價

C array of structs tutorial example explained#C # struct # array. ... <看更多>
struct array initialize 在 Initializing array of structures [duplicate] - Stack Overflow 的推薦與評價
... <看更多>
相關內容