为什么内部的Lua字符串存储他们做的方式是什么? [英] Why does internal Lua strings store the way they do?
问题描述
我是想将存储一堆常量一个简单的字符串表,我想:嘿!Lua中,让我使用一些有功能!
I was wanting a simple string table that will store a bunch of constants and I thought "Hey! Lua does that, let me use some of there functions!"
这主要是在lstring.h / lstring.c文件(我用5.2)
This is mainly in the lstring.h/lstring.c files (I am using 5.2)
我将显示code我很好奇第一。它从lobject.h
I will show the code I am curious about first. Its from lobject.h
/*
** Header for string value; string bytes follow the end of this structure
*/
typedef union TString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */
struct {
CommonHeader;
lu_byte reserved;
unsigned int hash;
size_t len; /* number of characters in string */
} tsv;
} TString;
/* get the actual string (array of bytes) from a TString */
#define getstr(ts) cast(const char *, (ts) + 1)
/* get the actual string (array of bytes) from a Lua value */
#define svalue(o) getstr(rawtsvalue(o))
正如所看到的,该数据被存储在结构的外侧。要获取字节流,你把TString的大小,加1,而你得到了的char *指针。
As you see, the data is stored outside of the structure. To get the byte stream, you take the size of TString, add 1, and you got the char* pointer.
这不是坏的编码有关系吗?它已经钻入米我的C类进行明确定义的结构。我知道我会在这里搅拌窝,但是你真的失去了那么多的速度/空间定义一个结构,报头数据,而不是数据定义一个指针值?
Isn't this bad coding though? Its been DRILLED into m in my C classes to make clearly defined structures. I know I might be stirring a nest here, but do you really lose that much speed/space defining a structure as header for data rather than defining a pointer value for that data?
推荐答案
这个想法可能是,你分配头和数据,而不是两个中的一个大块的数据:
The idea is probably that you allocate the header and the data in one big chunk of data instead of two:
TString *str = (TString*)malloc(sizeof(TString) + <length_of_string>);
除了具有只需一个电话来的malloc /免费的,你还可以减少内存碎片并增加内存的本地化。
In addition to having just one call to malloc/free, you also reduce memory fragmentation and increase memory localization.
但回答你的问题,是的,这类黑客通常是一个不好的做法,并应与极端小心。如果你这样做,你可能会想隐藏下的宏/内联函数层。
But answering your question, yes, these kind of hacks are usually a bad practice, and should be done with extreme care. And if you do, you'll probably want to hide them under a layer of macros/inline functions.
这篇关于为什么内部的Lua字符串存储他们做的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!