该篇文章将从Lua string的底层代码去分析字符串是如何创建、缓存、以及扩容的,深入分析了Lua字符串的整个工作原理。
字符串结构定义 Lua中字符串结构体定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #define  CommonHeader	GCObject *next; lu_byte tt; lu_byte marked typedef  struct  TString  {  CommonHeader;   lu_byte extra;     lu_byte shrlen;     unsigned  int  hash;   union  {     size_t  lnglen;       struct  TString  *hnext ;      } u; } TString; typedef  union  UTString {  L_Umaxalign dummy;     TString tsv; } UTString; 
 
字符串缓存 在创建字符串时,首先会从global_State的strcache缓存中查找看是否存在:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 TString *luaS_new  (lua_State *L, const  char  *str)   {  unsigned  int  i = point2uint(str) % STRCACHE_N;     int  j;   TString **p = G(L)->strcache[i];   for  (j = 0 ; j < STRCACHE_M; j++) {               if  (strcmp (str, getstr(p[j])) == 0 )        return  p[j];    }   for  (j = STRCACHE_M - 1 ; j > 0 ; j--)     p[j] = p[j - 1 ];       p[0 ] = luaS_newlstr(L, str, strlen (str));   return  p[0 ]; } 
 
创建一个字符串的时候,首先会在strcache中查找,第7行根据str计算出该str在strcache的索引位置,在该strcache位置上又有一个大小为2( STRCACHE_M )的TString数组,若在这个数组中找到相同的字符串,则返回cache中字符串对应的TString;若未找到,会将p[0]位置的TString挪到p[1]位置,而p[0]位置存放luaS_newlstr新创建的TString。
创建字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 TString *luaS_newlstr  (lua_State *L, const  char  *str, size_t  l)   {  if  (l <= LUAI_MAXSHORTLEN)       return  internshrstr(L, str, l);   else  {     TString *ts;     if  (l >= (MAX_SIZE - sizeof (TString))/sizeof (char ))       luaM_toobig(L);     ts = luaS_createlngstrobj(L, l);     memcpy (getstr(ts), str, l * sizeof (char ));     return  ts;   } } 
 
新建一个TString时,会判断字符串长度是否大于40( LUAI_MAXSHORTLEN ),对于长度大于40的str,会直接创建TString并返回,而对于长度40以内的short string,会从global_State中的一个stringtable(strt)查找并记录:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 static  TString *internshrstr  (lua_State *L, const  char  *str, size_t  l)   {  TString *ts;   global_State *g = G(L);   unsigned  int  h = luaS_hash(str, l, g->seed);   TString **list  = &g->strt.hash[lmod(h, g->strt.size)];   lua_assert(str != NULL );     for  (ts = *list ; ts != NULL ; ts = ts->u.hnext) {     if  (l == ts->shrlen &&         (memcmp (str, getstr(ts), l * sizeof (char )) == 0 )) {              if  (isdead(g, ts))           changewhite(ts);         return  ts;     }   }         if  (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2 ) {     luaS_resize(L, g->strt.size * 2 );     list  = &g->strt.hash[lmod(h, g->strt.size)];     }      ts = createstrobj(L, l, LUA_TSHRSTR, h);   memcpy (getstr(ts), str, l * sizeof (char ));   ts->shrlen = cast_byte(l);   ts->u.hnext = *list ;   *list  = ts;   g->strt.nuse++;   return  ts; } 
 
strt的数据结构类似于HashMap,它的初始化的数组长度为128,首先根据str计算得到的hash值(0~127),找到数组对应的下标索引,取出对应下标的list链表,10 ~ 18行是对该list进行遍历,若找到则直接返回;如未找到,则继续向下走。第21行, 如果 nuse(当前strt中TSring总数) 超过容量size(初始128)值,就会进行luaS_resize扩容操作(后续细讲),strt的容量将扩为原来的2倍。如果不需要扩容,第26行开始,会创建一个新的TString,并将其插入到当前list的头部。
扩容 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 void  luaS_resize  (lua_State *L, int  newsize)   {  int  i;   stringtable *tb = &G(L)->strt;   if  (newsize > tb->size) {       luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);     for  (i = tb->size; i < newsize; i++)       tb->hash[i] = NULL ;   }   for  (i = 0 ; i < tb->size; i++) {       TString *p = tb->hash[i];     tb->hash[i] = NULL ;     while  (p) {         TString *hnext = p->u.hnext;        unsigned  int  h = lmod(p->hash, newsize);        p->u.hnext = tb->hash[h];       tb->hash[h] = p;       p = hnext;     }   }   if  (newsize < tb->size) {            lua_assert(tb->hash[newsize] == NULL  && tb->hash[tb->size - 1 ] == NULL );     luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);   }   tb->size = newsize; } 
 
第7行,如果需要扩容,则调用luaM_reallocvector将 tb->hash 数组扩大到newsize (2倍),12行~22行对每一个数组位置list链表中每一个TString节点的元素重新计算hash值 ,并将其插入到对应数组中的链表头部位置处。