I was wondering if it will slow down my code if I have a bunch of small functions like

isNewRound[currentMove_] := Return[Mod[currentMove, 4] == 0];

which are getting called very frequently? My program is already a bit slower than I want it to be. I'm not sure how mathematica is handling functions. Thanks in advance!

  • 1
    $\begingroup$ RepeatedTiming shows that your function takes less than a microsecond to run so having small helper functions like this to make the rest of the code more readable is good practice. One point I would make is to not use Return in your function definitions, just use isNewRound[currentMove_] := Mod[currentMove, 4] == 0 $\endgroup$
    – Jason B.
    Dec 2 '21 at 22:23
  • 4
    $\begingroup$ Functions like RepeatedTiming, AbsoluteTiming, and EchoTiming can be really helpful for locating bottlenecks. $\endgroup$
    – Jason B.
    Dec 2 '21 at 22:24
  • 1
    $\begingroup$ If you are concerned about timing, try to use = instead of := and define isNewRound[currentMove_] = Divisible[currentMove, 4]. See here: immediate and delayed values. $\endgroup$
    – Roman
    Dec 3 '21 at 9:17
  • $\begingroup$ Also, make sure that your small functions are Listable and try to call them on entire lists of values instead of calling them for every value separately. $\endgroup$
    – Roman
    Dec 3 '21 at 9:30
  • $\begingroup$ Also, compile your function for specific input types (if known): isNewRound = Compile[{{c, _Integer}}, Mod[c, 4] == 0, CompilationTarget -> "C", RuntimeOptions -> "Speed", RuntimeAttributes -> {Listable}] $\endgroup$
    – Roman
    Dec 3 '21 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.