Abstract patterns
Richard A. O'Keefe
ok@REDACTED
Wed Mar 15 05:39:52 CET 2006
Bjorn Gustavsson wrote:
> What I meant by the phrase "implement efficiently" is that
performance should be comparable to that of records. If that
indeed would be possible to achive without inlining, we would be
^^^^^^^^^^^^^^^^
more interested in implementing abstract patterns.
I think we are comparing apples with centipedes here.
Let me show you a little table.
Definition is Records are Abstract patterns are
in same .erl file fast fast
because inlined if inlined
in an included file fast fast
because inlined if inlined
imported from INFINITELY SLOW as fast as ordinary
another module you can't do it function calls.
If you just took existing code and replaced -record declarations by the
appropriate abstract patterns (with corresponding changes elsewhere, of
course), you would expect the abstract pattern version to be the SAME
speed as the record version because it should be pretty much the SAME code.
Abstract patterns should be as fast as records except when they
are INFINITELY FASTER, because records can't be used at all.
Just how slow would abstract patterns be without inlining?
I wrote a little test case:
t1() ->
Xs = data(),
timer:tc(?MODULE, t1, [Xs,0]).
t1([{foo,K,_,_}|Xs], N) -> t1(Xs, N+K);
t1([], N) -> N.
t2() ->
Xs = data(),
timer:tc(?MODULE, t2, [Xs,0]).
t2([X|Xs], N) -> {K,_,_} = mod2:foo(X), t2(Xs, N+K);
t2([], N) -> N.
where in mod2,
foo({foo,X,Y,Z}) -> {X,Y,Z}.
t2() was 3.7 times slower than t1() [5.2 times slower if [native]].
This is pretty much a worst case comparison; even when compiled out-of-line
there are better things for abstract patterns to do than *literally* build
tuples. I wrote another test case, t3(), which avoided building a tuple
and then matching it again.
t3() was 1.2 times slower than t1() [2.1 times slower if [native]].
I would expect the kind of code one could generate, taking advantage
of the special restricted structure of abstract patterns, to be much
closer to the t3() time than the t2() time.
But remember, even t2() was INFINITELY FASTER than the analogue with
records, because there IS no analogue with records.
More information about the erlang-questions
mailing list