lisp - Performance difference between functions and pattern matching in Mathematica -
so mathematica different other dialects of lisp because blurs lines between functions , macros. in mathematica if user wanted write mathematical function use pattern matching f[x_]:= x*x
instead of f=function[{x},x*x]
though both return same result when called f[x]
. understanding first approach equivalent lisp macro , in experience favored because of more concise syntax.
so have 2 questions, there performance difference between executing functions versus pattern matching/macro approach? though part of me wouldn't surprised if functions transformed version of macros allow features listable
implemented.
the reason care question because of recent set of questions (1) (2) trying catch mathematica errors in large programs. if of computations defined in terms of functions, seems me keeping track of order of evaluation , error originated easier trying catch error after input has been rewritten successive application of macros/patterns.
the way understand mathematica is 1 giant search replace engine. functions, variables, , other assignments stored rules , during evaluation mathematica goes through global rule base , applies them until resulting expression stops changing.
it follows fewer times have go through list of rules faster evaluation. looking @ happens using trace
(using gdelfino's function g , h)
in[1]:= trace@(#*#)&@x out[1]= {x x,x^2} in[2]:= trace@g@x out[2]= {g[x],x x,x^2} in[3]:= trace@h@x out[3]= {{h,function[{x},x x]},function[{x},x x][x],x x,x^2}
it becomes clear why anonymous functions fastest , why using function
introduces additional overhead on simple setdelayed
. recommend looking @ introduction of leonid shifrin's excellent book, these concepts explained in detail.
i have on occasion constructed dispatch
table of functions need , manually applied starting expression. provides significant speed increase on normal evaluation none of mathematica's inbuilt functions need matched against expression.
Comments
Post a Comment