我为基于堆栈的语言编写了一个相当复杂的解析器,它将一个文件加载到内存中,然后通过比较标记来查看它是否被识别为操作数或指令。
每次我必须解析一个新的操作数/指令时,我都会将内存从文件缓冲区std::copy
复制到std::string
,然后执行`
if(parsed_string.compare("add") == 0) { /* handle multiplication */}
else if(parsed_string.compare("sub") == 0) { /* handle subtraction */ }
else { /* This is an operand */ }
不幸的是,所有这些拷贝都使解析变慢了。
我应该如何处理这个以避免所有这些拷贝?我一直认为我不需要分词器,因为语言本身和逻辑非常简单。
编辑:我正在添加代码以获取各种操作数和指令的拷贝
// This function accounts for 70% of the total time of the program
std::string Parser::read_as_string(size_t start, size_t end) {
std::vector<char> file_memory(end - start);
read_range(start, end - start, file_memory);
std::string result(file_memory.data(), file_memory.size());
return std::move(result); // Intended to be consumed
}
void Parser::read_range(size_t start, size_t size, std::string& destination) {
if (destination.size() < size)
destination.resize(size); // Allocate necessary space
std::copy(file_in_memory.begin() + start,
file_in_memory.begin() + start + size,
destination.begin());
}
最佳答案
这种复制是没有必要的。您可以对切片进行操作。
struct StrSlice {
StrSlice(const std::string& embracingStr, std::size_t startIx, std::size_t length)
: begin_(/* todo */), end_(/* todo */) // Assign begin_ and end_ here
{}
StrSlice(const char* begin, const char* end)
: begin_(begin), end_(end)
{}
// Define some more constructors
// Be careful about implicit conversions
//...
//Define lots of comparasion routines with other strings here
bool operator==(const char* str) const {
...
}
bool operator==(const StrSlice& str) const {
...
}
// You can take slice of a slice in O(1) time
StrSlice subslice(std::size_t startIx, std::size_t length) {
assert(/* do some range checks here */);
const char* subsliceBegin = begin_ + startIx;
const char* subsliceEnd = subsliceBegin + length;
return StrSlice(subsliceBegin, subsliceEnd);
}
private:
const char* begin_;
const char* end_;
};
希望您能理解。当然,这个切片会在相关字符串发生任何变化后中断,特别是内存重新分配。但除非您读取新文件,否则您的字符串似乎不会改变。
关于c++ - 更快地解析代码文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34093930/