Message Boards Message Boards

0
|
1024 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Replacing Module with Block without scoping issues?

Posted 11 months ago

I am wondering if I could safely replace Module with the Block scoring construct without having scoping issues in this function that computes the number of trailing zeroes in the factorial in arbitrary bases.

factorialZeros[n_Integer, b_Integer] /; n > 1 && b > 1 := 
 Module[{pfacs, pexpons},
  {pfacs, pexpons} = Transpose[FactorInteger[b]];
  Min[Floor[
    Map[Sum[Floor[n/#^j], {j, Floor[Log[#, n]]}] &, pfacs]/pexpons]]
  ]

I try to use Block because it's faster than Module.

POSTED BY: Peter Burbery
4 Replies

My point is that you are proposing a speed optimization that will be unlikely to serve any practical purpose. The code inside a scoping construct is almost always the slow part as compared to the overhead of the construct.

POSTED BY: Daniel Lichtblau

No, I learned this at a Wolfram Study Group.

POSTED BY: Peter Burbery

Did you perform timing tests to back this speed claim?

POSTED BY: Daniel Lichtblau

I found something helpful here: https://mathematica.stackexchange.com/questions/559/what-are-the-use-cases-for-different-scoping-constructs and here https://community.wolfram.com/groups/-/m/t/495564?sortMsg=Flat

I thought this was an interesting comment In practice, my advice would be to avoid using Block unless you know quite well why you need it. It is more error-prone to use it for variable localization than With or Module, because it does not prevent variable name collisions, and those will be quite hard to debug. One of the reasons people suggest to use Block is that they claim it is faster. While it is true, my opinion is that the speed advantage is minimal while the risk is high. I elaborated on this point here, where at the bottom there is also an idiom which allows one to have the best of both worlds. In addition to these reasons, as noted by @Albert Retey, using Block with the Dynamic - related functionality may lead to nasty surprises, and errors resulting from that may also be quite non-local and hard to find.

POSTED BY: Peter Burbery
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract