[SOLVED] Which of the following two pieces of code is faster or the same, and why?


-record(test, {a = 10}).

test(Test) when is_record(Test,test) -> somethings.


test(#test{} = Test) -> somethings.

which is faster or the same? why.


It’s not too hard to test with the compiler.
To do that, I wrote this module…

-module my_mod.
-export [t1/1, t2/1].

-record(test, {a = 10}).

t1(Test) when is_record(Test,test) -> somethings.

t2(#test{} = _Test) -> somethings.

Then, I run erlc -E my_mod.erl and this is the resulting expanded code:

-file("my_mod.erl", 1).



-record(test,{a = 10}).

t1({test, _} = Test) when true ->

t2({test, _} = _Test) ->

So, basically… it’s the same. Using is_record(Test, test) adds a useless guard (true) but that shouldn’t make a difference in terms of speed.

Furthermore, if you use erlc -S my_mod.erl, to generate assembly listings, you get:

{module, my_mod}.  %% version = 0

{exports, [{module_info,0},{module_info,1},{t1,1},{t2,1}]}.

{attributes, []}.

{labels, 9}.

{function, t1, 1, 2}.

{function, t2, 1, 4}.

{function, module_info, 0, 6}.

{function, module_info, 1, 8}.

As you can see, the two functions are, in fact, identical:

{function, …, 1, …}.

Answered By – Brujo Benavides

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *