你经常会看到这样的东西
std::map<std::string, somethingelse> m_named_objects;
或
std::string state;
//...
if(state == "EXIT")
exit();
else if(state == "california")
hot();
人们使用字符串纯粹是为了提高可读性。使用整数 ID 之类的东西可以轻松实现同样的事情。
现代编译器(msvc、g++ 等)通常可以针对这些类型的情况进行特殊优化吗?还是应该因为性能不佳或其他原因而避免这种情况?
最佳答案
Can modern compilers (msvc, g++, etc.) usually employ special optimizations for these types of cases?
据我所知,编译器不会进行此类优化。这绝对不是“标准”优化。
...where people use strings purely to make something more readable.
至少对于您的第二种情况,在我看来枚举更具可读性并且速度更快(因为整数比较相对于字符串比较而言相当便宜)。
enum State
{
Alabama,
Alaska,
Arizona,
Arkansas,
California,
Colorado,
Connecticut,
Delaware,
// ... More
};
// ...
State state = California;
if(state == California) { /* true */ }
关于c++ - 编译器通常会对字符串进行特殊优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262708/