Consider the following simple prolog program.
hairy(dog).
hairy(cat).
colour(dog, brown).
colour(dog, black).
colour(cat, grey).
colour(cat, white).
The following queries are logically equivalent.
?- colour(X, white), hairy(X).
?- hairy(X), colour(X, white).
Although the two queries are logically equivalent, the procedural execution is different.
Prolog's trace appears to confirm that one is more efficient than the other.
trace, colour(X, white), hairy(X).
Call:colour(_3844,white)
Exit:colour(cat,white)
Call:hairy(cat)
Exit:hairy(cat)
and
trace, hairy(X), colour(X, white).
Call:hairy(_4052)
Exit:hairy(dog)
Call:colour(dog,white)
Fail:colour(dog,white)
Redo:hairy(_476)
Exit:hairy(cat)
Call:colour(cat,white)
Exit:colour(cat,white)
Question: Is the first query actually more efficient than the second?
That is, is the longer set of trace steps for the second query misleading?
For example, in the shorter trace the first task is to find which X satisfies colour(X, white) and the trace exits immediately with X=cat, but in reality is the fact that it has to search through the previous three colour/2 facts hidden from us?
Motivation
I want to conclude that ordering the query predicates such that variables are instantiated correctly soonest is a good strategy for optimal or efficient queries. I'd welcome comments on this, which is the broader motivation for the question.