May 14, 2010

Erlang lists:keyfind VS proplists:get_value

Other Day @fdmananatold me that he discover that lists key find was much more fast then proplists. Since i use a lot of proplists on my code, i did some tests to check how much fast it is and i was shocked!

(af83@dakua.local)34> timer:tc(proplists,get_value,[99999,List]).
{8685,99999}
(af83@dakua.local)35> timer:tc(lists,keyfind,[99999,1,List]).
{829,{99999,99999}}

WOW! for a list of 100.000 elements proplists:get_value can be 10x slower then lists:key_find!

So now i’m using this encapsulation in order to maintain proplists syntax and avoid extra typing :)

proplist_get_value(Key,List)->
  case lists:keyfind(Key,1,List) of
    {_K,V}->
      V;
    false->
      undefined
  end.

Now the question is Why? why lists is much more faste then proplists? Our guess is that since lists functions are BIF’s, they must be build in C and proplists no, but this is just a guess, if someone has a better explanation please share.

  • proplists:get_value/2 do little bit different thing than lists:keyfind/2 See

    1> proplists:get_value(9999, [{9999,foo}]).
    foo
    2> proplists:get_value(9999, [9999]).
    undefined
    3> proplists:get_value(foo, [foo]).
    true
  • darkua
    Hello Hyneck

    I never notice that you could use proplists with atom lists, thanks for the correction. In the post i just did the case i was using, but i lost a some time and i believe i have a correct implementation of proplists:get_value/2 no Default value, please give it a try

    http://gist.github.com/402600

    Cheers
  • Try benchmark your implementation with this List = [[{X, a}|| X<-lists:seq(1,9999)]|[foo]] and try find value of foo. I think you will be surprised. You can fix it this way http://gist.github.com/402828. But it would still not behave like proplists:get_value/2. For example proplists:get_value(foo, [{foo}]) or proplists:get_value(foo, [foo, {foo, bar}]). Best what you can do is use lists:key_find if it is what you exactly want or use proplists if you really want proplists. If you would like know how something works, source code is ultimate documentation. For example I found that proplists:get_value(foo, [{foo}]) behaves differently by looking to source.
blog comments powered by Disqus