Quick question about short circuiting in RTMB

40 views
Skip to first unread message

pthomp...@gmail.com

unread,
Jan 14, 2025, 11:30:15 AM1/14/25
to TMB Users
Hi there,

I want to ask a small question about how short-circuiting works for Boolean operators within RTMB-wrapped functions. My understanding is that in regular R, the "&" (and) and "|" (or) operators do not short circuit (probably because they are vectorized?) but if you use "&&" or "||", those are (although you lose the vectorization. When you are comparing objects of length 1 with each other it is technically optimal to use these because it short-circuits and doesn't always need to check the second condition, if I understand correctly. However, I also realize that in some other languages, there is only one set of and/or operators and they short-circuit automatically.

I want to know if it makes a difference to use "&" versus "&&" within the R code of a function to be passed into RTMB::MakeADFun. Obviously this would only be relevant for cases when the two logicals being passed to "&" (or "&&") have length one and do not depend on any of the model parameters (but instead might depend on values of the data or the index of a loop or something). I realize it probably makes a minimal difference either way, but should I bother using "&&" or will RTMB convert it to something equivalent anyways? 

Thank you for any input you might have!

Kasper Kristensen

unread,
Jan 15, 2025, 6:30:18 AM1/15/25
to TMB Users
RTMB doesn't handle these operators, it's completely taken care of by base R. Whatever improves your code (performance/readability wise) with base R, I would stick with that pattern also in RTMB, even if the performance impact is smaller with RTMB.

pthomp...@gmail.com

unread,
Jan 15, 2025, 10:37:22 AM1/15/25
to TMB Users
Makes sense. Thank you Kasper!

Peter

Reply all
Reply to author
Forward
0 new messages