[erlang-questions] Why does Erlang have control structures?
Jayson Barley
jayson.barley@REDACTED
Mon Aug 27 23:44:53 CEST 2012
That is interesting. I didn't know that. I wonder why over 100 million
iterations I consistently get between 1 to 2 second differences in timing.
I know that there will be differences due to garbage collection, other
processes running, etc, but the is_greater_than_control/2 function always
outperforms the is_greater_than/2 function. Am I making a wrong assumption
and eventually the opposite would be true? Could you test the below code on
your system and let me know if you get similar results?
-module(test).
-compile(export_all).
is_true(true) ->
true;
is_true(false) ->
false.
is_greater_than(X, Y) ->
is_true(X>Y).
is_greater_than_control(X, Y) ->
if
X>Y ->
true;
true -> % works as an 'else' branch
false
end.
test_if(X, X, _) ->
done;
test_if(X, Max, Fun) ->
Fun(X, Max),
test_if(X + 1, Max, Fun).
test_if(Max) ->
[timer:tc(test, test_if, [0, Max, fun is_greater_than/2]),
timer:tc(test, test_if, [0, Max, fun is_greater_than_control/2])].
8> test:test_if(100000000).
[{7234000,done},{5718999,done}]
On Mon, Aug 27, 2012 at 2:00 PM, Andrzej Sliwa <andrzej.sliwa@REDACTED>wrote:
> there is no difference in speed at all,
>
> > switch_signal({signal, _What, _From, _To}) ->
> > true;
> > switch_signal({signal, _What, _To}) ->
> > true;
> > switch_signal(_Else) ->
> > false.
>
> is compiled internally to one function with case
> so code speed is equal
>
> there is only difference in readability.
>
> On Aug 27, 2012, at 10:56 PM, Jayson Barley <jayson.barley@REDACTED>
> wrote:
>
> > I am not sure I understand why we have them. For instance I can take the
> following code
> > is_greater_than(X, Y) ->
> > if
> > X>Y ->
> > true;
> > true -> % works as an 'else' branch
> > false
> > end.
> > And make it
> > is_true(true) ->
> > true;
> > is_true(false) ->
> > false.
> >
> > is_greater_than(X, Y) ->
> > is_true(X>Y).
> > I can do the same thing with case statements
> > is_valid_signal(Signal) ->
> > case Signal of
> > {signal, _What, _From, _To} ->
> > true;
> > {signal, _What, _To} ->
> > true;
> > _Else ->
> > false
> > end.
> > Becomes
> > switch_signal({signal, _What, _From, _To}) ->
> > true;
> > switch_signal({signal, _What, _To}) ->
> > true;
> > switch_signal(_Else) ->
> > false.
> >
> > is_valid_signal(Signal) ->
> > switch_signal(Signal).
> >
> > I know that the control structures are a little bit faster, not much,
> but I find that the function form is more readable.
> > _______________________________________________
> > erlang-questions mailing list
> > erlang-questions@REDACTED
> > http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120827/16a6b990/attachment.htm>
More information about the erlang-questions
mailing list