pages tagged stub http://meng6net.localhost/tag/stub/ <p><small>Copyright © 2005-2020 by <code>Meng Lu &lt;lumeng3@gmail.com&gt;</code></small></p> Meng Lu's home page ikiwiki Tue, 16 May 2017 23:59:39 +0000 use cheaper functions when possible http://meng6net.localhost/use_cheaper_functions_when_possible/ http://meng6net.localhost/use_cheaper_functions_when_possible/ computing mathematica programming stub tip Tue, 16 May 2017 23:59:39 +0000 2017-05-16T23:59:39Z <p>Mathematica is functional and has high code density. It tends to lead one to use more powerful function than the task really necessarily requires. Because high code density typically means it needs to check many things to figure out default (or <code>Automatic</code>) values, it slows down the program unnecessarily sometimes.</p> <h2><code>Join</code> vs. <code>Flatten</code></h2> <p>Use <code>Join</code> to join lists, not Flatten, if you know it's safe. <code>Join</code> is faster and uses less memory.</p> <pre><code>In[6]:= Quit[] In[1]:= data=Table[RandomVariate[NormalDistribution[],100],{20}]; In[2]:= m1=MemoryInUse[]; Do[t=Flatten[data,1],{10000}]//AbsoluteTiming m2=MemoryInUse[]; m2-m1 Out[3]= {3.9662268,Null} Out[5]= 74704 </code></pre> <p>Compare it to</p> <pre><code>Join@@list In[2]:= m1=MemoryInUse[]; Do[t=Join@@data,{10000}]//AbsoluteTiming m2=MemoryInUse[]; m2-m1 Out[3]= {0.1730099,Null} Out[5]= 36240 </code></pre>