Optimize Code 

Module creates unique variables each time it is executed. By writing a function using Block and globally unique variables, repeated execution is sped up because the variable-creation step is omitted.

Remove Module in favor of Block with globally unique variables.

In[1]:=
Click for copyable input
X

Create an inactive function.

In[2]:=
Click for copyable input
X
Out[2]=

Apply the transformation.

In[3]:=
Click for copyable input
X
Out[3]=

Activate the code and the transformed code to make definitions for fModule and fBlock.

In[4]:=
Click for copyable input
X

Compare values for random test values.

In[5]:=
Click for copyable input
X
Out[5]=

Comparing timings for a large set of test values shows a factor of 2.5 speed improvement.

In[6]:=
Click for copyable input
X
Out[6]=