It has been a while since I started my journey with Elixir and I can say I'm more than happy so far by the journey.
Elixir is an extraordinary language but now I'm not going to share my experience with Elixir, I'll do it in another post.
I wanted instead to start with a collections of basic performance tips.
Always keep in mind time complexity when you write code:
Lists
`0(1) at the front` for `LookUp` and `Updates` makes clear that we should use the `[ head | tail ]` pattern every time is possible.
Maps and Tuples
While `Maps` provide a more complex data structure, if we are dealing with few field a `Tuple` should be your preferred choice as the `LookUp` time complexity is `0(1)`.
Counting Item vs > 1
Lists as written above are linked lists so when we try to count the items inside a list eg. `Enum.count( my_list)`; it is `O(n)` complexity operation.
This is why in this specific case `if Enum.count( my_list) > 1 do` it is better to use `if Enum.empty( my_list) do`. In that case we avoid to count the entire list as it is not a stored info but a O(n) time complexity operation while the second case using the `head | tail` pattern is very fast
Checking empty strings
Strings can be considered like `LinkedList` for counts as there is not a stored information for fast access.
In case of understanding if a String is empty it is better to use `my_string_var == ""` rather than `String.length( my_string_var) > 0`.
In that case we avoid to count all the characters of the string, as it is not a stored info but a O(n) time complexity operation while the first approach is just a simple comparison.
I hope you will find them helpful!
No comments :
Post a Comment