小于255的整数的性能与未签名的字符一样快吗?

发布于 2025-01-27 06:40:52 字数 590 浏览 2 评论 0原文

我知道一个未签名的角色的大小为8位,整数的大小为32位。

但是我想知道我是否在255以下的两个整数之间执行一个操作,可以肯定地说,它与对该整数相同值的两个无符号字符执行相同的操作一样快?

示例:

int Int2 = 0x10;
int Int1 = 0xff;

unsigned char Char0 = 0x10;
unsigned char Char1 = 0xff;

Int1  + Int2 ; // Is calculating this
Char0 + Char1; // Faster than this??

更新: 让我们按照某人的建议将其放在上下文中

for (unsigned char c=0;c!=256;c++){ // does this loop

   std::cout<<c; // dont mind this line it can be any statement
}

for (int i=0;i!=256;i++){ // perform faster than this one??

   std::cout<<i;// this too
}

I know that an unsigned character's size is 8 bits, and the size of an integer is 32 bits.

But I want to know if I perform an operation between two integers below 255, is it safe to say it is as fast as performing the same operation on two unsigned characters of the same value of that integers?

Example:

int Int2 = 0x10;
int Int1 = 0xff;

unsigned char Char0 = 0x10;
unsigned char Char1 = 0xff;

Int1  + Int2 ; // Is calculating this
Char0 + Char1; // Faster than this??

Update:
Let's put this in the context as someone suggested

for (unsigned char c=0;c!=256;c++){ // does this loop

   std::cout<<c; // dont mind this line it can be any statement
}

for (int i=0;i!=256;i++){ // perform faster than this one??

   std::cout<<i;// this too
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妄司 2025-02-03 06:40:52

我知道一个未签名的角色的大小为8位

这在C ++中不一定总是如此。但这可能是正确的,特别是C ++的实现。

整数的大小为32位。

C ++中有几种整数类型。实际上,字符类型也是整数类型。

  int1 + int2; //正在计算这个
char0 + char1; //比这个更快?
 

当用作大多数二进制运算符的操作数时,在int的整数中, 被提升为int(在极少数情况下)。示例中的两个操作员在促销后都在int上运行。您根本不使用结果,因此编译器不需要生成任何代码,因此在这个琐碎的示例中它们应该同样快。

一个代码是否比另一个代码更快取决于许多因素。不可能准确猜测没有上下文的方式。

I know that an unsigned character's size is 8 bits

This is not necessarily always the case in C++. But it may be true in particular implementation of C++.

and the size of an integer is 32 bits.

There are several integer types in C++. In fact, character types are integer types as well.

Int1  + Int2 ; // Is calculating this
Char0 + Char1; // Faster than this??

Integers of lower rank than int are promoted to int (or unsigned int in rare cases) when used as operand of most binary operators. Both operators in the example operate on int after the promotion. You don't use the result at all, so there's no need for the compiler to produce any code, so they should be equally fast in this trivial example.

Whether one piece of code is faster than the other depends on many factors. It's not possible to accurately guess which way it would go without context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文