我为基于堆栈的语言编写了一个相当复杂的解析器,它将文件加载到内存中,然后通过比较令牌来查看它是否被识别为操作数或指令.
每次我必须解析一个新的操作数/指令我std::copy
将内存从文件缓冲区转移到a std::string
然后执行`
if(parsed_string.compare("add") == 0) { /* handle multiplication */} else if(parsed_string.compare("sub") == 0) { /* handle subtraction */ } else { /* This is an operand */ }
不幸的是,所有这些副本都使解析速度变慢.
我应该如何处理这个以避免所有这些副本?我一直认为我不需要一个tokenizer,因为语言本身和逻辑非常简单.
编辑:我正在添加代码,我获取各种操作数和指令的副本
// 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::vectorfile_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()); }
Minor Threat.. 6
这种复制不是必需的.你可以操作切片.
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_; };
我希望你明白这个主意.当然,在关联字符串中的任何更改之后,此片段将会中断,尤其是内存重新分配.但是看起来你的字符串没有改变,除非你读了一个新文件.
这种复制不是必需的.你可以操作切片.
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_; };
我希望你明白这个主意.当然,在关联字符串中的任何更改之后,此片段将会中断,尤其是内存重新分配.但是看起来你的字符串没有改变,除非你读了一个新文件.