Re: SetDelayed and Evaluate

*To*: mathgroup at smc.vnet.net*Subject*: [mg104497] Re: SetDelayed and Evaluate*From*: Szabolcs Horvát <szhorvat at gmail.com>*Date*: Sun, 1 Nov 2009 17:57:00 -0500 (EST)*References*: <hcjiul$jmr$1@smc.vnet.net>

On 2009.11.01. 10:04, Peter wrote: > Hi group, > > after years of experience with Mathematica I've got a simple (?) > problem: > > When answering to a question on the student support forum (http:// > forums.wolfram.com/student-support/topics/21448/) I tried fo myself > the folowing variants: > f[z_?NumericQ]:=Compile[{{x,_Real}},x-x^2][z]; > g[z_?NumericQ]:=Evaluate[Compile[{{x,_Real}},x-x^2]][z]; > and got the following results: > In[6]:= Timing[Do[NMaximize[f[x],x],{1000}]] > Out[6]= {35.871,Null} > In[7]:= Timing[Do[NMaximize[g[x],x],{1000}]] > Out[7]= {35.962,Null} > > ~1 ms per NMaximize is OK, because there are background-processes > running. > > But I expect f to compile x-x^2 at every call to f and g to compile > once on time of definition. Therefore I expected g to be significantly > faster than f. > > Where am I wrong? > Dear Peter, If you look under 'More Information' in the documentation, you'll see "Evaluate only overrides HoldFirst, etc. attributes when it appears directly as the head of the function argument that would otherwise be held." This is not true for SetDelayed in your example because of the presence of [z] after Evaluate[...]. You can check that the Compile[...] part is not evaluated before the definition is created using Information[g]. I would like to note though that (unless I'm mistaken), NMaximize should automatically compile the function it's given. So the simplest solution, NMaximize[x - x^2, x], is likely also the fastest.