RE: Cases, Throw, and Catch
- To: mathgroup at smc.vnet.net
- Subject: [mg24197] RE: [mg24182] Cases, Throw, and Catch
- From: Wolf Hartmut <hwolf at debis.com>
- Date: Fri, 30 Jun 2000 01:57:26 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
> -----Original Message-----
> From: Mark Fisher [SMTP:me.fisher at atl.frb.org]
To: mathgroup at smc.vnet.net
> Sent: Thursday, June 29, 2000 4:51 AM
> To: mathgroup at smc.vnet.net
> Subject: [mg24182] Cases, Throw, and Catch
>
> I just noticed that it is much faster to Throw and Catch from Cases than
> to have Cases return the first match on its own. Does anyone know why
> this is so and what, if anything, is to be learned?
>
> Here is the example:
>
> In[1]:=
> xtab = Table[x, {10^6}];
>
> In[2]:=
> Cases[xtab, x, Infinity, 1] // Timing
>
> Out[2]=
> {0.172 Second, {x}}
>
> In[3]:=
> Catch @ Cases[xtab, Throw[{x}], Infinity, 1] // Timing
>
> Out[3]=
> {0. Second, {x}}
>
> In[4]:=
> ytab = Append[xtab, y];
>
> In[5]:=
> Cases[ytab, y, Infinity, 1] // Timing
>
> Out[5]=
> {0.437 Second, {y}}
>
> In[6]:=
> Catch @ Cases[ytab, Throw[{y}], Infinity, 1] // Timing
>
> Out[6]=
> {0. Second, {y}}
[Wolf Hartmut]
Hello Mark,
your observation is an optical illusion, see
In[23]:= Attributes[Cases]
Out[23]= {Protected}
So in
In[6]:= Catch at Cases[ytab, Throw[{y}], Infinity, 1] // Timing
Out[6]= {0.01 Second, {y}}
Throw will execute immediately without Cases having worked at all! Compare
this with
In[21]:= Catch at Cases[ytab, y :> Throw[{y}], Infinity, 1] // Timing
Out[21]= {1.242 Second, {y}}
and on my machine I get
In[5]:= Cases[ytab, y, Infinity, 1] // Timing
Out[5]= {1.232 Second, {y}}
which is fairly consistent. Select however is much slower here
In[10]:= Select[ytab, y === # &, 1] // Timing
Out[10]= {32.307 Second, {y}}
which should not be astonishing for this application. Here two other
procedures to compare
In[16]:= Catch[If[y === #, Throw[{y}]] & /@ ytab] // Timing
Out[16]= {46.396 Second, {y}}
In[19]:= Do[If[y === ytab[[i]], Return[y]], {i, 1, Length[ytab]}] // Timing
Out[19]= {54.087 Second, y}
Kind regards, Hartmut