C ++ 11用户定义的文字比普通类型转换慢吗?

are C++11 user defined literals slower than normal type casting?

1) 这些在运行时是否比另一个快?哪个以及为什么?
2) 这发生在编译时还是运行时?

unsigned short operator"" _ushort( unsigned long long arg ){ return arg; }

unsigned short my_var = 0x1234;          // using type and literal
auto my_var = unsigned short(0x1234);    // using auto and casting literal to type
auto my_var = 0x1234_ushort;             // using auto and user defined literal to cast

编辑: 使用 constexpr 有帮助吗?

constexpr unsigned short operator"" _ushort( unsigned long long arg ){ return arg; }

所有这些都是在编译时初始化的,因此对它们中的任何一个都没有运行时影响。

让我们看看生成的程序集...使用这个工具:https://gcc.godbolt.org

clang生成的程序集是:(修改你的代码编译)

对于这个输入,

inline unsigned char operator "" _kx ( unsigned long long arg ){ return arg; }

unsigned char my_var = 0x14;          // using type and literal
auto my_var2 = (unsigned char) 0x1234;    // using auto and casting literal to type
auto my_var3 = 0x1234_kx;             // using auto and user defined literal to cast

生成的程序集是

my_var:
        .byte   20                      # 0x14

my_var2:
        .byte   52                      # 0x34

my_var3:
        .byte   52                      # 0x34

因此,没有性能下降……而是灵活性的提高…… 尽管运算符函数似乎仍在某些编译器版本中以某些标志创建...。这些值在编译时初始化

https://godbolt.org/g/YuJyQd