宏和函数的区别

宏和函数的区别?

宏有点儿像编译时的表达式生成函数。正如函数会通过一组参数得到一个返回值,宏可以进行表达式的变换,这些宏允许程序员在最后的程序语法树中对表达式进行任意的转化。

—w3cshool

看看这个例子

help?> @time
  @time

  A macro to execute an expression, printing the time it took to execute, the
  number of allocations, and the total number of bytes its execution caused to
  be allocated, before returning the value of the expression.

  See also @timev, @timed, @elapsed, and @allocated.

  julia> @time rand(10^6);
    0.001525 seconds (7 allocations: 7.630 MiB)
  
  julia> @time begin
             sleep(0.3)
             1+1
         end
    0.301395 seconds (8 allocations: 336 bytes)
  2

julia> @macroexpand @time 1 + 1
quote
    #= util.jl:154 =#
    local #6#stats = (Base.gc_num)()
    #= util.jl:155 =#
    local #8#elapsedtime = (Base.time_ns)()
    #= util.jl:156 =#
    local #7#val = 1 + 1
    #= util.jl:157 =#
    #8#elapsedtime = (Base.time_ns)() - #8#elapsedtime
    #= util.jl:158 =#
    local #9#diff = (Base.GC_Diff)((Base.gc_num)(), #6#stats)
    #= util.jl:159 =#
    (Base.time_print)(#8#elapsedtime, (#9#diff).allocd, (#9#diff).total_time, (Base.gc_alloc_count)(#9#diff))
    #= util.jl:161 =#
    (Base.println)()
    #= util.jl:162 =#
    #7#val
end
julia> @time 1 + 1 
  0.000004 seconds (4 allocations: 160 bytes)
2

我自己的理解是普通的函数无法将语句作为参数,而宏可以以语句为参数,这就开拓了很多的可能性。并且宏在编译的时候就被展开了,实际运行时并没有切换的开销,会比函数运行更快。