hey all, I am comparing 2 cases for merging 2 lists, the best way would be probably to use list1++list2, but lets forget about that for this question. So the 2 cases are-
# for merging 2 lists -> list1 & list2
#case1 use Enum.reduce
Enum.reduce(list1,list2,&[&1 | &2])
#case2 -> merge(list1,list2)
def merge([],list2) do
list2
end
def merge(list1, list2) do
[head | remaining_list1] = list1
list2 = [head | list2]
merge(remaining_list1, list2)
end
is there any difference between these 2 methods?
benchee claims that for 200 size lists and in case of merging 4 such lists these are the stats-
Benchmarking Enum.reduce ...
Benchmarking merge ...
Name ips average deviation median 99th %
merge 30.72 K 32.55 μs ±16.74% 32 μs 37 μs
Enum.reduce 14.41 K 69.39 μs ±61.47% 68 μs 76 μs
Comparison:
merge 30.72 K
Enum.reduce 14.41 K - 2.13x slower +36.84 μs
can someone please explain what is the difference in implementation of these 2 cases?
I think what you’re looking for is Enum.reduce(list1, list2, &[&1 | &2]). Not sure how that will benchmark against your merge function, my guess is they’ll be pretty similar
Nitpick: I don’t know what the compiler optimization passes do with them, but Enum.reduce on a list should naively be very very slightly faster because it has one term in its guard clause instead of two.