指针转换成本 [英] Cost Of Casting Pointers

查看:80
本文介绍了指针转换成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Eveybody,你好.

我四处搜寻,搜寻并没有找到明确的答案.

有人说C ++ static_cast不需要为指针花任何钱,这是真的吗?
以及static_cast与C样式强制转换有何不同?



就CPU周期(而不是编译时间,运行时)而言,C样式转换/C ++静态转换是否昂贵?

它用于
的铸造

 LPVOID 



我想这是过早的乐观.

抱歉,如果这是转发:)

解决方案

在回答之前,我有点懒得去研究,尽管我认为您会发现任何指针强制转换实际上都会是免费的.虽然不是强制性的,例如将double转换为int.

指针始终是指针.唯一改变的是指针所指向的数据类型.不能说相同的数字.数字有各种各样的不同类型-字节,单词,整数,短裤,多头,双精度数,浮点数等.因此,从一个类型转换为另一个类型必然涉及某种类型的转换.确实,性能影响会因发生的转换而有所不同,但总会有一次转换.

另一方面,如果我们看一下指针,则可以看到不需要遍历相同的问题.在32位系统上,指针的长度为32位.正如我提到的,它实际指向的数据类型无关紧要,指针的大小仍然相同,并且指向相同的东西-内存位置.在我的理解中,对指针执行强制转换只是警告编译器注意该指针现在将用于访问的数据类型.当编译器将偏移量计算为数组,或者您(程序员)执行手动指针算术时,这一点很重要.


如果我可以恭敬地补充,优化时还有其他(远)重要的事情要考虑.如果您还没有,我建议您通过探查器运行您的代码,并查看所有执行时间都花在了哪里.
干杯,
S


有关static_cast的更详细的答案是此处 [ ^ ]


Hi Eveybody.

i searched around, googled and did not find definite answer to this.

some one said that C++ static_cast does not cost anything for pointers, is this true ?
and how does static_cast differ from C style casts ?

also

is C style casting / C++ static cast expensive, in terms of CPU cycles ( not compile time, runtime )

its for casting of

LPVOID



i guess this is premature optomization.

Sorry if this is a repost :)

Thanks in Advance.

解决方案

I''m a little too lazy to research before I answer, though I think you''ll find that any pointer casting is essentially going to be for free. Though this would not be the case for casting say, a double to an int, for instance.

A pointer is always a pointer.The only thing that changes is the type of data it points to. The same can''t be said for a number. Numbers come in all sorts of different types - bytes, words, ints, shorts, longs, doubles, floats etc, etc. So, to cast from one to another does necessarily involve a conversion of some type. While it is true that the performance hit will vary depending on the conversion happening, there will always be a conversion.

If on the other hand we look at pointers, we can see that the same problem does not need to be traversed. On a 32 bit system, a pointer is 32bits long. As I mentioned, it doesn''t matter what type of data it actually points to, the pointers are all still the same size and refer to the same thing - a memory location. In my understanding, performing a cast on a pointer simply alerts the compiler to the data type that this pointer will now be used to access. This is important when the compiler calculates offsets into arrays or you (the programmer) does manual pointer arithmetic.


If I could respectfully add, there are other (far)more important things to look at when optimizing. If you''ve not already, I''d suggest running your code through a profiler and seeing where all of the execution time is being spent.
Cheers,
S


A more detailed answer about static_cast is here[^]


这篇关于指针转换成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆