使用宏定义与 const 变量
Using macro definition vs const variable
我对预处理器宏有一些疑问。这是要讨论的 2 个不同代码片段的示例;
tmp.h
#define DEFAULT_STRING "default_value"
tmp.cpp
void tmpFunc(std::string newValue){
m_stringValue = newValue;
if(newValue.isEmpty())
newValue = DEFAULT_STRING;
}
和第二个版本
tmp.h
const std::string m_defaultValue = "default_value"
tmp.cpp
void tmpFunc(std::string newValue){
m_stringValue = newValue;
if(newValue.isEmpty())
newValue = m_defaultValue;
}
所以我的问题是;
- 第一个版本是否增加了二进制大小(与第一个第二个相比)?
- 第二个版本是否消耗更多内存(与第一个版本相比)?
- 这两种实现对性能有何影响?哪个应该 运行 更快,为什么?
- preferable/beneficial在什么条件下?
- 有没有更好的实现设置默认值的方法?
谢谢。
两者都很糟糕,第二个比第一个好一点。
最好的方法是使用
constexpr char DEFAULT_STRING[] = "default_value";
有关 constexpr
的更多信息,请参阅 When should you use constexpr capability in C++11?
Does the first version increase the binary size (comparing the first second)?
没有。由于该字符串只使用一次,因此在编译后的文件中只会出现一次。
Does the second version consume more memory (comparing the first one)?
没有。它以几乎相同的方式处理内存。
What are the performance impacts of both implementations? Which should run faster and why?
两种实现都复制字符串:该方法按值接收 newValue
,复制它。我猜这种复制将主导性能。
但是,一如既往地衡量性能,只需对其进行衡量 - 这应该很容易,因为您已经实现了两个版本的代码。
Which is preferable/beneficial in which condition?
宏不是 C++ 中惯用的解决方案。使用 const
字符串。
Is there any better way for implementation of setting the default value?
通过引用接收新字符串。除此之外,没有那么多。我在这里假设默认值是一个短字符串,例如 "none"
或 "default"
。这些字符串有short string optimization,所以你如何存储它并不重要。
与性能一样,如果您发现您的方法是性能瓶颈,请对其进行优化。不知道就不要优化
我对预处理器宏有一些疑问。这是要讨论的 2 个不同代码片段的示例;
tmp.h
#define DEFAULT_STRING "default_value"
tmp.cpp
void tmpFunc(std::string newValue){
m_stringValue = newValue;
if(newValue.isEmpty())
newValue = DEFAULT_STRING;
}
和第二个版本
tmp.h
const std::string m_defaultValue = "default_value"
tmp.cpp
void tmpFunc(std::string newValue){
m_stringValue = newValue;
if(newValue.isEmpty())
newValue = m_defaultValue;
}
所以我的问题是;
- 第一个版本是否增加了二进制大小(与第一个第二个相比)?
- 第二个版本是否消耗更多内存(与第一个版本相比)?
- 这两种实现对性能有何影响?哪个应该 运行 更快,为什么?
- preferable/beneficial在什么条件下?
- 有没有更好的实现设置默认值的方法?
谢谢。
两者都很糟糕,第二个比第一个好一点。
最好的方法是使用
constexpr char DEFAULT_STRING[] = "default_value";
有关 constexpr
的更多信息,请参阅 When should you use constexpr capability in C++11?
Does the first version increase the binary size (comparing the first second)?
没有。由于该字符串只使用一次,因此在编译后的文件中只会出现一次。
Does the second version consume more memory (comparing the first one)?
没有。它以几乎相同的方式处理内存。
What are the performance impacts of both implementations? Which should run faster and why?
两种实现都复制字符串:该方法按值接收 newValue
,复制它。我猜这种复制将主导性能。
但是,一如既往地衡量性能,只需对其进行衡量 - 这应该很容易,因为您已经实现了两个版本的代码。
Which is preferable/beneficial in which condition?
宏不是 C++ 中惯用的解决方案。使用 const
字符串。
Is there any better way for implementation of setting the default value?
通过引用接收新字符串。除此之外,没有那么多。我在这里假设默认值是一个短字符串,例如 "none"
或 "default"
。这些字符串有short string optimization,所以你如何存储它并不重要。
与性能一样,如果您发现您的方法是性能瓶颈,请对其进行优化。不知道就不要优化