【发布时间】:2019-04-16 07:53:41
【问题描述】:
我想在我的函数get_color(image) 中获取 Elixir 字节列表中的前 3 个字节,其中 image 是一个结构体,hex 定义为字节列表。
现在我知道这种模式匹配方式是这样的:
def get_color(image) do
[a,b,c | _] = image.hex
[a,b,c]
end
我的初始代码是:
def get_color(image) do
{color, _rest_of_array} = image.hex |> Enum.split(3)
color
end
我想知道这两种方法是否同样有效,或者 Enum.split 是否有其他一些可能使其变慢的后台工作?或者它可能会消耗更多内存,因为它还必须创建列表的另一半?
我的代码的基准测试(基于答案):
Name ips average deviation median 99th %
match 184.23 M 5.43 ns ┬▒149.37% 0 ns 31 ns
enum.split 2.35 M 425.32 ns ┬▒15.78% 454 ns 614 ns
Comparison:
match 184.23 M
enum.split 2.35 M - 78.36x slower +419.89 ns
【问题讨论】:
-
询问这两种方法是否“同样有效”是假设 only 区别在于代码。如果机器由于其他情况而处于重负载状态,即使是在同一台机器上运行的两个代码片段也可能会在性能上有所不同。 “过早的优化……”
标签: elixir