Edit: I changed the sample code to get at my question better. Slowdown due to accessing a shared variable is a much more relevant issue (to me at least) than slowdown due to writing to a shared variable.
I've been frustrated to find that parallelizing my code often makes it slower. After long wondering why this is, I think I found that SetSharedVariable and SetSharedFunction are to blame.
Naïvely I would expect these functions to work efficiently and create little overhead. Yet instead they seem to be hugely problematic. Here's a basic example:
SetSharedVariable[foo]
foo = 6;
ParallelTable[
foo^foo^foo;
, {j, 1, 2}] // AbsoluteTiming
ParallelTable[
Module[{foo2 = 6},
foo2^foo2^foo2;]
, {j, 1, 2}] // AbsoluteTiming
(*
{0.053959, {Null, Null}}
{0.015549, {Null, Null}}
*)
Can someone explain why the overhead for accessing a value every iteration is so much larger just because it's a shared variable? Even better, can someone explain or link to a resource for understanding how to use SetSharedVariable without huge slowdowns (this happens for my longer calculations too), and perhaps the truly correct situations in which to use it? (I often use it just to shut up Mathematica from spewing errors, which I'm sure is not wise.)
(I use Mathematica 11.0.0.0 on a MacBook with Dual Core)