Re: Big speed difference between styles?
- From: Jan Wielemaker <jan@xxxxxxxxxxxxxxxxxxx>
- Date: 16 Sep 2006 16:24:04 GMT
On 2006-09-16, roschler <robert.oschler@xxxxxxxxx> wrote:
I want to know what the performance difference is between the three
following styles of writing a predicate where I want to restrict the
domain of one of the arguments.
Suppose I have a predicate and I only want to accept three particular
values for the first argument. I could do the following:
% CASE 1 - use clause head unification
pred(value_one) :-
pred_aux(value_one).
pred(value_two) :-
pred_aux(value_one).
pred(value_three) :-
pred_aux(value_one).
pred_aux(X) :-
% do some more stuff with X
....
Or I could do:
% CASE 2 - use term comparison with disjunctions.
pred(X) :-
(X == value_one ; X == value_two; X == value_three),
% do some more stuff with X
...
Or I could do:
% CASE 3 - use the member function with a list of items.
pred(X) :-
member(X, [value_one, value_two, value_three]),
% do some more stuff with X
I'm guessing that CASE 2 and CASE 3 are slower than CASE 1 since
Prolog can't do a simple unification but has to examine rules or a list
instead. But how much slower? Sometimes it's much more convenient,
especially during prototyping, to just tweak a list of disjunctions or
a list used in a member/2 call, then to have to create extra predicate
clauses to control the domain of an argument.
You miss one option:
pred(X) :-
ok_for_aux(X),
pred_aux(value_one).
ok_for_aux(value_one).
ok_for_aux(value_two).
ok_for_aux(value_three).
This -in my opinion- is the best option. It is efficient (only very
slightly less than CASE 1), it avoids rewriting _and_ it gives you the
opportunity to give the test on X a name (ok_for_aux here).
Is the performance hit, if there is one, really worth worrying about?
Depends what you are doing. In general I'd advice to write using the
style you consider most readable. If the program gets too slot, run the
profiler to find the performance bottleneck and consider optimizing
there. Read "The Craft of Prolog" with many invaluable tips to keep your
code both readable and fast. In many cases these things do not bite in
Prolog. In cases where they do you can consider source rewriting using
term_expansion/2. That shouldn't be your first worry, but it is good to
know that if readability asks for a different representation than
performance you can opt for automatic transformation.
Cheers --- Jan
.
- References:
- Big speed difference between styles?
- From: roschler
- Big speed difference between styles?
- Prev by Date: Re: The n-knights problem
- Next by Date: comp.lang.prolog Frequently Asked Questions
- Previous by thread: Big speed difference between styles?
- Next by thread: Re: Big speed difference between styles?
- Index(es):
Relevant Pages
|