gpt4 book ai didi

integer - 为什么使用整数而不是长整型?

转载 作者:行者123 更新时间:2023-12-03 05:41:42 25 4
gpt4 key购买 nike

我经常看到与 Overflow 错误相关的问题.

我的问题是为什么使用integer变量声明而不是仅仅将所有数值变量(不包括double等)定义为long

除非您在 for 循环中执行类似操作,可以保证该值不会超过 32,767 限制,否则是否会对性能产生影响或导致不使用 long?

最佳答案

Integer variables are stored as 16-bit (2-byte) numbers

Office VBA Reference

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers

Office VBA Reference

因此,好处是减少了内存空间。 Integer 占用的内存是 Long 的一半。现在,我们讨论的是 2 个字节,因此它不会对单个整数产生真正的影响,只有在处理大量整数(例如大型数组)并且内存使用至关重要时才需要考虑。

但是32位系统上,内存使用量减半是以性能为代价的。当处理器实际使用 16 位整数执行某些计算(例如递增循环计数器)时,该值会默默地转换为临时 Long,而不会受益于更大范围的数字。溢出仍然会发生,并且处理器用于存储计算值的寄存器将占用相同数量的内存(32 位)。 Performance may even be hurt因为必须转换数据类型(在非常低的级别)。

不是我正在寻找的引用,但是......

My understanding is that the underlying VB engine converts integers to long even if its declared as an integer. Therefore a slight speed decrease can be noted. I have believed this for some time and perhaps thats also why the above statement was made, I didnt ask for reasoning.

ozgrid forums

这是我正在寻找的引用。

Short answer, in 32-bit systems 2 byte integers are converted to 4 byteLongs. There really is no other way so that respective bits correctly lineup for any form of processing. Consider the following

MsgBox Hex(-1) = Hex(65535) ' = True

Obviously -1 does not equal 65535 yet the computer is returning the correctanswer, namely"FFFF" = "FFFF"

However had we coerced the -1 to a long first we would have got the rightanswer (the 65535 being greater than 32k is automatically a long)

MsgBox Hex(-1&) = Hex(65535) ' = False

"FFFFFFFF" = "FFFF"

Generally there is no point in VBA to declare "As Integer" in modernsystems, except perhaps for some legacy API's that expect to receive anInteger.

pcreview forum

最后我找到了msdn documentation我真的很认真地在寻找。

Traditionally, VBA programmers have used integers to hold smallnumbers, because they required less memory. In recent versions,however, VBA converts all integer values to type Long, even if they'redeclared as type Integer. So there's no longer a performance advantageto using Integer variables; in fact, Long variables may be slightlyfaster because VBA does not have to convert them.

根据评论进行澄清:整数仍然需要更少的内存来存储 - 一个大的整数数组将需要比具有相同尺寸的 Long 数组少得多的 RAM(几乎正好是一半)尽可能多,您可以在任务管理器中自行检查)。但由于处理器需要使用 32 位内存块,因此 VBA 在执行计算时暂时将整数转换为长整型

<小时/>

因此,总而言之,现在几乎没有充分的理由使用 Integer 类型。 除非您需要与需要 16 位 int 的旧 API 调用进行互操作,或者您正在使用小整数的大型数组并且内存非常宝贵。除非 p>

One thing worth pointing out is that some old API functions may be expecting parameters that are 16-bit (2-byte) Integers and if you are on a 32 bit and trying to pass an Integer (that is already a 4-byte long) by reference it will not work due to difference in length of bytes.

感谢 Vba4All 指出这一点。

关于integer - 为什么使用整数而不是长整型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26409117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com