I want to get the first 3 bytes in a list of bytes in Elixir in my function get_color(image), where image is a struct with hex defined as the list of bytes.
Now I know the pattern matching way of this would be something like:
def get_color(image) do
[a,b,c | _] = image.hex
[a,b,c]
end
My initial code was however:
def get_color(image) do
{color, _rest_of_array} = image.hex |> Enum.split(3)
color
end
I want to know if both approaches are just as efficient, or whether Enum.split does some other background work that may make it slower? Or perhaps it consumes more memory because it also has to create the other half of the list?
Benchee test for my code (based on answer):
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