What’s the difference between `1L` and `1`?

So, @James and @Brian explained what 3L means. But why would you use it?

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).

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!

…and as @Gavin pointed out, the range for integers is roughly -2e9 to 2e9.

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).

Leave a Comment