gpt4 book ai didi

C++解释器概念问题

转载 作者:可可西里 更新时间:2023-11-01 18:37:22 26 4
gpt4 key购买 nike

我用 C++ 为我创建的语言构建了一个解释器。

设计中的一个主要问题是我在语言中有两种不同的类型:数字和字符串。所以我必须传递一个像这样的结构:

class myInterpreterValue
{
myInterpreterType type;
int intValue;
string strValue;
}

这个类的对象每秒传递大约一百万次,例如:在我的语言中的倒计时循环。

Profiling指出:85%的性能被字符串模板的分配函数吃掉了。

我很清楚这一点:我的解释器设计不佳并且没有充分使用指针。然而,我别无选择:在大多数情况下我不能使用指针,因为我只需要制作拷贝。

如何应对呢?这样的类(class)是更好的主意吗?

vector<string> strTable;
vector<int> intTable;
class myInterpreterValue
{
myInterpreterType type;
int locationInTable;
}

所以类只知道它代表什么类型和在表中的位置

然而,这也有缺点:我必须向字符串/整数 vector 表添加临时值,然后再次删除它们,这会再次消耗大量性能。

  • 求助,Python 或 Ruby 等语言的解释器如何做到这一点?他们不知何故需要一个结构来表示语言中的值,例如可以是 int 或 string 的东西。

最佳答案

我怀疑很多值不是字符串。因此,您可以做的第一件事就是在不需要时删除 string 对象。把它放到一个 union 中。另一件事是,您的许多字符串可能都很小,因此如果您将小字符串保存在对象本身中,就可以摆脱堆分配。 LLVM 有 SmallString的模板。然后你可以使用字符串实习,正如另一个答案所说的那样。 LLVM 有 StringPool为此类:调用 intern("foo") 并获取一个智能指针,该指针指向可能也被其他 myInterpreterValue 对象使用的共享字符串。

union 可以这样写

class myInterpreterValue {
boost::variant<int, string> value;
};

boost::variant 为您做类型标记。如果你没有提升,你可以像这样实现它。在 C++ 中还不能获得可移植的对齐,因此我们将一些可能需要一些大对齐的类型推送到存储 union 中。

class myInterpreterValue {
union Storage {
// for getting alignment
long double ld_;
long long ll_;

// for getting size
int i1;
char s1[sizeof(string)];

// for access
char c;
};
enum type { IntValue, StringValue } m_type;

Storage m_store;
int *getIntP() { return reinterpret_cast<int*>(&m_store.c); }
string *getStringP() { return reinterpret_cast<string*>(&m_store.c); }


public:
myInterpreterValue(string const& str) {
m_type = StringValue;
new (static_cast<void*>(&m_store.c)) string(str);
}

myInterpreterValue(int i) {
m_type = IntValue;
new (static_cast<void*>(&m_store.c)) int(i);
}
~myInterpreterValue() {
if(m_type == StringValue) {
getStringP()->~string(); // call destructor
}
}
string &asString() { return *getStringP(); }
int &asInt() { return *getIntP(); }
};

你明白了。

关于C++解释器概念问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2660554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com