There are a number of situations where objects may unwittingly be created and destroyed. This can reduce the usability of RAM through fragmentation.
底下有舉例, 一個常見的例子就是字串的串接操作, 每次使用 '+' 來串接字串時, 就會牽涉到 3 個字串物件, '+' 號左右各一個, 以及串接後建立的新字串物件。最近就剛好遇到一個案例, 使用 urequests.get 向 OpenWeatherMap 網站查詢器項資料, 為了讓人看清楚整個參數的結構, 所以寫成這樣 (整個程式不只這樣):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
res = urequests.get( # API 網址 | |
"https://api.openweathermap.org/data/2.5/weather?" + | |
"q=" + "Taipei" + ",TW" + # 指定城市與國別 | |
"&units=metric&lang=zh_tw&" + # 使用攝氏單位 | |
"appid=" + # 以下填入註冊後取得的 API key | |
".....................") |
結果程式一執行, 雖然可以看到結果, 但是程式結束後要回到交談模式時, ESP8266 就會當掉。只要把其中 "q=" + ... 這邊改成不要串接, 直接寫成 "q=Taipei,TW" + 就可以了, 還害我找了好久的問題。畢竟在單晶片控制板上跑的 Python 和在一般電腦上跑得不一樣, 撰寫程式時要特別小心。