vctrs::vec_size() vs NROW()

I am starting to use vctrs in a real project, and I am thankful for the added type and size stability.

In my use case, I would like to return vctrs::vec_size() for vectors and otherwise return a sensible length without erroring out. I see 2 options:

  1. Just use NROW().
  2. Check vec_is() first and then decide whether to use NROW() or vec_size().

(1) is risky if there are valid vectors for which NROW() disagrees with vec_size(), but I hesitate to adopt (2) because it is much slower than NROW().

library(bench)
library(vctrs)
f <- function(x) {
  if (vec_is(x)) {
    vec_size(x)
  } else {
    NROW(x)
  }
}
x <- "abc"
mark(
  NROW = NROW(x),
  vec_size = vec_size(x),
  custom = f(x)
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 NROW          390ns    585ns  1555426.        0B    156. 
#> 2 vec_size      363ns    507ns  1812045.     2.2KB      0  
#> 3 custom       2.08µs   2.89µs   324205.    17.7KB     97.3
x <- new.env()
mark(
  NROW = NROW(x),
  custom = f(x)
)
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 NROW          495ns    642ns  1484035.        0B        0
#> 2 custom       1.51µs   1.84µs   521306.        0B        0

Created on 2019-12-10 by the reprex package (v0.3.0)

Are there vectors for which NROW() and vec_size() disagree?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.