查看lua佔用內存大小
想要獲取lua元素的size,無法直接使用sizeof,需要使用collectgarbage
local function getMem()
return collectgarbage("count")
end
collectgarbage("stop")
local before = getMem()
local a = {}
local after = getMem()
print("using mem“, (after-before)*1024)
lua5.1.4 輸出結果:using mem, 32
lua table佔用內存分析
也就是說一個空的table佔用內存大小32bit。接下來我們看看空table的數據結構:
lobject.h 338
typedef struct Table {
CommonHeader; //-6bit
lu_byte falgs; //-1bit
lu_byte lsizenode; //-1bit
struct Table *metatable; //-4bit
TValue *array; //-4bit
Node *node; //-4bit
Node *lastfree; //-4bit
GCObject *gclist; //-4bit
int sizearray; //-4bit
}Table;
lobject.h 43
#define CommonHeader GCObject* next; lu_byte tt; lu_byte marked;
llimits.h 27
typedef unsigned char lu_byte;
lua table arraylist佔用內存分析
local a ={ 0 }佔用內存是多少?48bit
a的大小 = {} + 0,{}=32bit,0在table中放在TValue *array中,所以TValue的大小是我們要關注的。查看lua中關於TValue的定義:
typedef union {
GCObject *gc;
void *p;
lua_Number n;
int b;
} Value;
#define TValuefileds Value value; int tt
typedef struct lua_TValue {
TValuefields;
} TValue;
lua_number 是double,所以 sizeof(double) + sizeof(int) = 12bit。考慮到結構體字節對齊, 結構中佔用最大空間的類型所佔用的字節數(sizefo(double)=8)的倍數,最終 sizeof(TValue) = 16bit
lua table hashMap佔用內存分析
local a = { {} }佔用內存是多少? 80bit
element | size |
---|---|
外層table | 32 |
Tvalue | 16 |
內層table | 32 |
local a = {x = 0}佔用內存是多少?64bit
x=0在table結構體中放置在Node *node中,查看源碼關於Node的定義:
typedef union TKey {
struct {
Tvaluefileds;
struct Node *next;
}nk;
Tvalue tvk
} TKey;
typedef struct Node {
TValue i_val;
TKey i_key;
} Node;
sizeof(Node) = sizeof(TValue) + sizeof(TKey) = 16 + 16 = 32
sizeof(Table) = 32 + n* 16 + 全部數組元素的size + m*32 + 全部hash部分元素的size
估算的情況下可以認爲全部是數組或者hash
究竟是arrayList還是hashMap?
local a= {0}
local b = { [0] = 0 }
元素0在a中放在arraylist中,而在b中放在hashMap中。其實lua table在resize的時候會對arraylist和hashMap進行優化,所以數組有可能在hashMap中存儲。關於這部分內用會在以後專題分析。就估算而言,完全可以認爲table中全部爲數組或者hashMap。