Skip to content

Instantly share code, notes, and snippets.

@josevalim josevalim/foo.erl Secret
Last active Aug 29, 2015

Embed
What would you like to do?
-module(foo).
-compile(export_all).
-record(foo, { a = 1, b = 2, c = 3, d = 4, e = 5 }).
map_new() ->
#{ a => 1, b => 2, c => 3, d => 4, e => 5 }.
record_new() ->
#foo{}.
map_get(#{ e := E }) ->
E.
record_get(#foo{ e = E }) ->
E.
map_put(M) ->
M#{ e := 10 }.
record_put(R) ->
R#foo{ e = 10 }.
map_access(M) ->
case M of
#{ e := E } -> E;
O -> O:e()
end.
record_access(M) ->
M:e().
e() ->
13.
e(#foo{ e = E }) ->
E.
bench() ->
io:format("Warm up~n"),
bench(fun() -> map_new() end, 10),
bench(fun() -> record_new() end, 10),
io:format("New 1000~n"),
bench(fun() -> map_new() end, 100000),
bench(fun() -> record_new() end, 100000),
io:format("New 100000~n"),
bench(fun() -> map_new() end, 10000000),
bench(fun() -> record_new() end, 10000000),
Map = map_new(),
Rec = record_new(),
io:format("Get 1000~n"),
bench(fun() -> map_get(Map) end, 100000),
bench(fun() -> record_get(Rec) end, 100000),
io:format("Get 100000~n"),
bench(fun() -> map_get(Map) end, 10000000),
bench(fun() -> record_get(Rec) end, 10000000),
io:format("Put 1000~n"),
bench(fun() -> map_put(Map) end, 100000),
bench(fun() -> record_put(Rec) end, 100000),
io:format("Put 100000~n"),
bench(fun() -> map_put(Map) end, 10000000),
bench(fun() -> record_put(Rec) end, 10000000),
io:format("Access 1000~n"),
bench(fun() -> map_access(Map) end, 100000),
bench(fun() -> record_access(Rec) end, 100000),
io:format("Access 100000~n"),
bench(fun() -> map_access(Map) end, 10000000),
bench(fun() -> record_access(Rec) end, 10000000),
io:format("Access fallback 1000~n"),
bench(fun() -> map_access(foo) end, 100000),
bench(fun() -> record_access(foo) end, 100000),
io:format("Access fallback 100000~n"),
bench(fun() -> map_access(foo) end, 10000000),
bench(fun() -> record_access(foo) end, 10000000),
init:stop().
bench(Fun, Times) ->
TimesFun = fun() -> times(Fun, Times) end,
Pid = spawn_link(fun() ->
io:format("~p~n", [timer:tc(TimesFun, [])])
end),
receive
{ 'EXIT', Pid, normal } -> ok
end.
times(_Fun, 0) -> ok;
times(Fun, Times) -> Fun(), times(Fun, Times - 1).
@MSch

This comment has been minimized.

Copy link

commented Apr 10, 2014

results on my macbook with 17

Warm up
{1,ok}
{0,ok}
New 1000
{2199,ok}
{1629,ok}
New 100000
{166437,ok}
{158678,ok}
Get 1000
{2297,ok}
{2251,ok}
Get 100000
{222137,ok}
{215232,ok}
Put 1000
{3687,ok}
{3538,ok}
Put 100000
{412577,ok}
{364117,ok}
Access 1000
{2322,ok}
{4451,ok}
Access 100000
{244921,ok}
{461319,ok}
Access fallback 1000
{3713,ok}
{3954,ok}
Access fallback 100000
{422447,ok}
{403837,ok}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.