(2) Lua源码系列----字符串的源码

本文深入探讨了Lua 5.3.4版本中的字符串实现,包括字符串的数据结构,如长字符串和短字符串的区别,以及它们的内存分配。接着详细阐述了字符串哈希计算的过程,特别是如何引入随机种子来避免哈希冲突。此外,文章还介绍了字符串创建的机制,特别是短字符串的内部化。对于字符串的比较,文章分析了短字符串通过地址比较以及长字符串的具体比较方法。最后提到了字符串表的调整对性能的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lua 的字符串 #

Lua 版本 5.3.4

1 字符串的数据结构

1.1 字符串分类

从 5.2.0版本开始,Lua 开始区分长字符串和短字符串,“长短”长度的标准定义在 llimits.h
#define LUAI_MAXSHORTLEN 40

“长短” 类型的定义在 lobject.h

/* Variant tags for strings */
#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4))  /* short strings */
#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4))  /* long strings */

1.2 字符串的结构

/*
** Header for string value; string bytes follow the end of this structure
** (aligned according to 'UTString'; see next).
** **字符串的头部,字符串的真正内容在这个结构后面**
*/
typedef struct TString {
  CommonHeader;
  lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
                  /* 对于短字符串:这个标示是否是保留字,长字符串:是否已经哈希① */
  lu_byte shrlen;  /* 短字符串的长度 */
  unsigned int hash;
  union {
    size_t lnglen;  /* 长字符串的长度 */
    struct TString *hnext;  /* 短字符串:linked list for hash table */
  } u;
} TString;


/*
** Ensures that address after this type is always fully aligned.
*/
typedef union UTString {
  L_Umaxalign dummy;  /* 内存对齐 */
  TString tsv;
} UTString;

补充1: 字符串申请内存大小
#define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char))

说明①: 长字符串是惰性求hast值

unsigned int luaS_hashlongstr (TString *ts) {
  lua_assert(ts->tt == LUA_TLNGSTR);
  if (ts->extra == 0) {  /* no hash? */
    ts->hash = luaS_has
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值