You might find this to be a fun example of how simple-seeming optimizations can be much more trouble than you might expect.
For _years_, in Matlab (and perhaps other languages), x^2 was much, much slower than x*x. You might think it's surprising that a company with Mathworks' resources couldn't fix this for so long. In Julia we optimize it: julia> foo1(x) = x*x foo1 (generic function with 1 method) julia> foo2(x) = x^2 foo2 (generic function with 1 method) julia> foo3(x) = x^3 foo3 (generic function with 1 method) julia> @code_llvm foo1(5) define i64 @julia_foo1_21463(i64) { top: %1 = mul i64 %0, %0 ret i64 %1 } julia> @code_llvm foo2(5) define i64 @julia_foo2_21471(i64) { top: %1 = mul i64 %0, %0 ret i64 %1 } julia> @code_llvm foo3(5) define i64 @julia_foo3_21472(i64) { top: %1 = mul i64 %0, %0 %2 = mul i64 %1, %0 ret i64 %2 } ("mul" means multiply, which means it's expanding x^3 as (x*x)*x.) BUT, this seemingly-trivial optimization proved to be a lot of hassle: see https://github.com/JuliaLang/julia/issues/6506 and the discussions that preceded it. Best, --Tim On Wednesday, May 11, 2016 02:34:56 AM Ford Ox wrote: > From docs: > > macro r_str(p) > > > Regex(p) > > end > > > > > > That’s all. This macro says that the literal contents of the string > > literal r"^\s*(?:#|$)" should be passed to the > > @r_str macro and the result of that expansion should be placed in the > > syntax tree where the string literal occurs. In > > other words, the expression r"^\s*(?:#|$)" is equivalent to placing the > > following object directly into the syntax > > tree: > > Regex("^\\s*(?:#|\$)") > > > > > > Not only is the string literal form shorter and far more convenient, but > > it is also more efficient: since the regular > > expression is compiled and the Regex object is actually created when the > > code is compiled, the compilation occurs > > only once, rather than every time the code is executed. Consider if the > > regular expression occurs in a loop: > > for line = lines > > m = match(r"^\s*(?:#|$)", line) > > if m == nothing > > # non-comment > > else > > # comment > > end > > end > > > > Shouldn't the compiler optimize this code *on its own* like this ? > > re = Regex("^\\s*(?:#|\$)") > for line = lines > m = match(re, line) > if m == nothing > # non-comment > else > # comment > end > end > > This is kind of optimization which is really easy to detect and and execute. > How is that so that julia is not able to do that?