查看lua占用内存大小
想要获取lua元素的size,无法直接使用sizeof,需要使用collectgarbage
1
2
3
4
5
6
7
8
9local 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
1
2
3
4
5
6
7
8
9
10
11
12typedef 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
1
2#define CommonHeader GCObject* next; lu_byte tt; lu_byte marked;
llimits.h 27
1
2typedef unsigned char lu_byte;
lua table arraylist占用内存分析
local a ={ 0 }占用内存是多少?48bit
a的大小 = {} + 0,{}=32bit,0在table中放在TValue *array中,所以TValue的大小是我们要关注的。查看lua中关于TValue的定义:
1
2
3
4
5
6
7
8
9
10
11
12
13typedef 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的定义:
1
2
3
4
5
6
7
8
9
10
11
12
13typedef 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?
1
2
3local a= {0} local b = { [0] = 0 }
元素0在a中放在arraylist中,而在b中放在hashMap中。其实lua table在resize的时候会对arraylist和hashMap进行优化,所以数组有可能在hashMap中存储。关于这部分内用会在以后专题分析。就估算而言,完全可以认为table中全部为数组或者hashMap。
最后
以上就是激情翅膀最近收集整理的关于估算lua内存大小的全部内容,更多相关估算lua内存大小内容请搜索靠谱客的其他文章。
发表评论 取消回复