Ask Your Question

Is it bad practice to declare variables in a callback?

asked 2020-05-06 10:43:50 -0500

ozangungor gravatar image

updated 2020-05-13 21:21:52 -0500

fvd gravatar image

Hi all, I would like to know if I should avoid creating new variables in a callback function since the callback will be executed each time I receive new data, thus creating a new variable again and again. Thanks

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-05-06 11:02:27 -0500

DanRose gravatar image

updated 2020-05-06 11:03:21 -0500

Performance is a black art and at the end of the day, you have to profile it to be sure. Don't worry about performance until you have reason to believe it's an issue.

That said, it's not bad practice. In fact it's good practice to keep variable declarations close to their usage to avoid accidental shared mutable state. Variables on the stack are super lightweight - even if a variable is in a tight loop, declaring the variable inside the loop will not be an issue, since the compiler will generally optimize it out.

Only when the object is (entirely or partly) on the heap or involves contended resources like locks will there be a performance impact and you should measure it to see if the impact is even worth worrying about.

edit flag offensive delete link more



Just to add some ROS-flavour to this answer (or ROS 1): never create Publishers, Subscribers or Action servers or clients in callbacks. Nor NodeHandles or TF Listeners or Buffers.

It's perhaps not the kind of performance which @rosberry is asking about, nor what @DanRose is writing about, but creating entities in callbacks for which the initialisation and/or correct functioning takes time/depends on how long ago they were created is not a good idea and will most of the times not work.

Setting up subscriptions, publications and action servers and clients as well as TF buffers takes time. Your callback typically doesn't give it that time, so things will not work.

Edit: and yes, I wrote "never" there. As this is software, and the search space is almost unlimited, you will most likely come across situations or code where it is actually necessary or ...(more)

gvdhoorn gravatar image gvdhoorn  ( 2020-05-06 11:14:46 -0500 )edit

Thank you both for the explanations, it was very helpful.

ozangungor gravatar image ozangungor  ( 2020-05-07 05:01:46 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2020-05-06 10:43:50 -0500

Seen: 241 times

Last updated: May 13 '20