Here's a simple question. This is my code for an exercise for the book I'm slowly going thru in my free time, that checks if (unbalanced) binary tree is ordered (e.g. left <= parent, parent <= right).
For is_ordered function, one could write out all clauses with nested records for every combination, and get rid of compare_nodes; however the code looks cleaner with compare_nodes. Question is, will code without compare_nodes be faster, or is compiler smart enough to track const correctness/optimize compare_node away in some other way (for real-world code too, not just this simple example)?
-record(node, {l=false,r=false,v}).
is_ordered(false) -> true;
is_ordered(#node{l=L,r=R} = N) ->
compare_nodes(L,N) and compare_nodes(N,R) and is_ordered(L) and is_ordered(R).
compare_nodes(L,R) when L == false; R == false -> true;
compare_nodes(#node{v=LV},#node{v=RV}) -> LV =< RV.
I'm not sure which version will be faster.
Best way to find out is to try both and measure.
But always go first for the more clearer and cleaner code. Only if you have a performance problem first profile where the bottleneck is and then optimize it.
As it looks to me the other suggested version has lots of duplicated code. A violation of the IMHO very important "Once and only once" rule can only be justified by a really significant performance boost.
And don't forget:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" (D. Knuth)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With