“1L"和“1"有什么区别? [英] What's the difference between `1L` and `1`?
问题描述
我经常看到符号1L
(或2L
、3L
等)出现在R代码中.1L
和 1
有什么区别?1==1L
计算结果为 TRUE
.为什么在R代码中使用1L
?
I often seen the symbol 1L
(or 2L
, 3L
, etc) appear in R code. Whats the difference between 1L
and 1
? 1==1L
evaluates to TRUE
. Why is 1L
used in R code?
推荐答案
所以,@James 和@Brian 解释了什么 3L 的含义.但是为什么你会使用它?
So, @James and @Brian explained what 3L means. But why would you use it?
大多数时候它没有区别 - 但有时您可以使用它来让您的代码运行得更快并消耗更少的内存.双精度(数字")向量每个元素使用 8 个字节.整数向量每个元素仅使用 4 个字节.对于大型向量,浪费的内存更少,CPU 消耗更少(因此通常更快).
Most of the time it makes no difference - but sometimes you can use it to get your code to run faster and consume less memory. A double ("numeric") vector uses 8 bytes per element. An integer vector uses only 4 bytes per element. For large vectors, that's less wasted memory and less to wade through for the CPU (so it's typically faster).
这主要适用于使用索引时.这是一个将整数向量加 1 将其转换为双向量的示例:
Mostly this applies when working with indices. Here's an example where adding 1 to an integer vector turns it into a double vector:
x <- 1:100
typeof(x) # integer
y <- x+1
typeof(y) # double, twice the memory size
object.size(y) # 840 bytes (on win64)
z <- x+1L
typeof(z) # still integer
object.size(z) # 440 bytes (on win64)
...但还要注意,过度使用整数可能很危险:
...but also note that working excessively with integers can be dangerous:
1e9L * 2L # Works fine; fast lean and mean!
1e9L * 4L # Ooops, overflow!
...正如@Gavin 指出的那样,整数的范围大约是 -2e9 到 2e9.
...and as @Gavin pointed out, the range for integers is roughly -2e9 to 2e9.
但需要注意的是,这适用于当前的 R 版本 (2.13).R 可能会在某个时候改变这一点(64 位整数会很好,它可以启用长度 > 2e9 的向量).为安全起见,您应该在需要最大整数值时使用 .Machine$integer.max
(并为最小值取反).
A caveat though is that this applies to the current R version (2.13). R might change this at some point (64-bit integers would be sweet, which could enable vectors of length > 2e9). To be safe, you should use .Machine$integer.max
whenever you need the maximum integer value (and negate that for the minimum).
这篇关于“1L"和“1"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!