ahsanghalib
I am new to Elixir, learning it. I have a list of US Cities from this github link https://raw.githubusercontent.com/grammakov/USA-cities-and-states/master/us_cities_states_counties.csv
I am trying to process this, remove the duplicate after removing the last two columns.
I have a NodeJS script doing the same but it’s way faster the elixir. Can anyone help me improve it.
Elixir : 55.9859 sec | Node: 4.2381143870018425 sec
Elixir Script.
#!/usr/bin/env elixir
defmodule Benchmark do
def measure(function) do
time =
function
|> :timer.tc()
|> elem(0)
|> Kernel./(1_000_000)
|> to_string()
IO.puts(time <> " sec")
end
end
defmodule UsCitiesStates do
def uniq([]), do: []
def uniq([head | tail]) do
[head | for(x <- uniq(tail), x != head, do: x)]
end
def process() do
IO.puts("stated...")
list =
File.stream!("./us_cities_states_counties.csv")
|> Stream.map(&String.trim(&1))
|> Stream.map(&String.split(&1, "|"))
|> Stream.filter(fn
["city" | _] -> false
_ -> true
end)
|> Stream.map(&(Stream.drop(&1, -2) |> Enum.to_list()))
cities =
list
|> Enum.to_list()
|> uniq()
IO.inspect(cities)
IO.inspect(length(cities))
end
end
Benchmark.measure(&UsCitiesStates.process/0)
Elxir Result
stated...
[
["Holtsville", "NY", "New York"],
["Adjuntas", "PR", "Puerto Rico"],
["Aguirre", "PR", "Puerto Rico"],
["Aibonito", "PR", ...],
["Maunabo", ...],
[...],
...
]
29860
55.9859 sec
Node
import fs from "node:fs";
import readline from "node:readline/promises";
import { PerformanceObserver, performance } from "node:perf_hooks";
const perf = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.duration / 1000, "sec");
}
});
perf.observe({ entryTypes: ["measure"], buffered: true });
(async function main() {
try {
performance.mark("start");
const data = [];
const rl = readline.createInterface({
input: fs.createReadStream("./us_cities_states_counties.csv"),
});
const clean = (msg, err) => {
console.log(msg);
if (msg === "error") console.log("error", err || "none");
if (msg === "close") {
performance.mark("end");
performance.measure("fs-stat", "start", "end");
console.log(data);
}
};
rl.on("line", (ln) => {
const d = ln.toString().trim();
if (d === "city|state_short|state_full|county|city_alias") return;
const city = d.split("|").slice(0, -2).join(",");
if (data.includes(city)) return;
data.push(city);
});
rl.on("close", () => clean("close"));
} catch (e) {
console.log(e);
}
})();
Node Result
close
[
[ 'Holtsville', 'NY', 'New York' ],
[ 'Adjuntas', 'PR', 'Puerto Rico' ],
[ 'Aguada', 'PR', 'Puerto Rico' ],
... 29760 more items
]
4.2381143870018425 sec
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted”
Version...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #blog-post
- #ai
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
kip
A more idiomatic Elixir version might look like this:
Which when benchmarked (using Benchee) against your original version is quite a bit faster and more memory efficient:
dimitarvp
Damn. That’s 95% identical to what I was writing right now. Kudos, you’re fast!
ahsanghalib
So, I need to use external library…
Can you explain why Nimble is fast ?
I have checked it’s code, its using erlang functions mostly ?
Basically I should start with learning erlang.
kip
Profiling would be required to establish if Nimble_Csv is the main contributor to the speed up.
I suspect it isn’t. I think your uniq function is the primary contributor since it processes the list an exponential number of times in the comprehension.
You don’t need to learn erlang to use Elixir. But over time you’re likely to find it helpful and eventually you’ll likely even enjoy it (although opinions vary).
Treat nimble_csv as a black box like you would in any CSV implementation. It uses metaprogrammjng to generate efficient code. But that’s not something you should be focused on early in Elixir use.
ahsanghalib
Thanks for help,
Yes, you are right about
uniqfunction. I changed it toEnum.uniq()& got0.252773 seckip
Elixir doesn’t try to do everything and external dependencies are encouraged to build out more capabilities. A lot of thought has been put into the hex library manager by the developers to obviate many of the challenges in other ecosystems. Therefore in general you shouldn’t be concerned about using external dependencies - it’s very normal with Elixir and totally expected.
ahsanghalib
yes, elixir or erlang external libs are good. but its not about their quality.
when i first start learning a new language i usually try to avoid external libs as much as possible. & also when i use libs is mostly after reading the code in github to get the gist of it.
aungmyooo2k17
Check this library when you process with big file
> https://hexdocs.pm/flow/Flow.html
al2o3cr
This is the main performance issue in the code above. It does a loop inside a recursion making comparisons, so every element of the list ends up compared to every other element of the list. That means
O(N^2)for an input list of lengthN, and bad performance for large datasets.If that explanation is too hand-wavy, imagine running this
uniqon a list with four elements[:a, :b, :c, :d]:uniq([:a, :b, :c, :d])headbound to:auniq([:b, :c, :d])headbound to:buniq([:c, :d])headbound to:cuniq([:d])headbound to:duniq([])[][]tohead(:d) and skip ones that match[:d | []]aka[:d][:d]tohead(:c) and skip ones that match[:c | [:d]], aka[:c, :d][:c, :d]tohead(:b) and skip ones that match[:b, :c, :d][:b, :c, :d]tohead(:a) and skip ones that match[:a | [:b, :c, :d]]aka[:a, :b, :c, :d]Here’s another implementation that might be slightly faster because it doesn’t construct intermediate results for values that have already been seen. It uses a simple list
seento track which elements have already appeared in the result.HOWEVER
It’s labeled “slightly” faster because it still has the same core inefficiency -
head in seendoes its work by comparingheadto each element ofseenone at a time, so the more unique elements there are in the input the slower it goes.What this kind of problem needs is a fast way to answer “has this value been seen before?”
The solution chosen by
Enum.uniq(and other parts of stdlib likeMapSet) is aMap. Looking up a key in a map is much faster (O(log N)for large maps) so this code will work much better thanSomewhatFasterUniq:Compare the implementation in
Enumfor lists:https://github.com/elixir-lang/elixir/blob/44d3faad45a32d9648792b54e46e8ac27283ffb8/lib/elixir/lib/enum.ex#L4776-L4783
dimitarvp
That’s fair but file format parsers should be external libraries. You don’t want to reinvent well-known (but sometimes difficult to implement, like HTTP) formats and protocols. It’s just not a productive expenditure of your time.
(At the same time, nothing is stopping you from inspecting
NimbleCSVcode and take lessons from it.)And for your task in particular using a CSV parser (configured with a custom separator as @kip’s coding snippet demonstrates) is a very good idea due to corner cases, f.ex. imagine if one of the values in the CSV file actually used the
|character that you use as a separator – and you’ll get more values in that row (i.e. if you normally have 5 values per row but you’ll get 6 or more values for the row that uses|inside a value). A proper parser will catch that, your homemade code will very likely not.