Last active
July 21, 2017 14:17
-
-
Save stevegrossi/bbca6678f610562d5048415e42f59fe7 to your computer and use it in GitHub Desktop.
Elixir parsing stringy integers: rescue vs. regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule StringToIntegerBench do | |
use Benchfella | |
@word "string" | |
@integer "1234" | |
bench "regex for word" do | |
if numeric_string?(@word) do | |
@word |> String.to_integer | |
else | |
@word | |
end | |
end | |
bench "regex for integer" do | |
if numeric_string?(@integer) do | |
@integer |> String.to_integer | |
else | |
@integer | |
end | |
end | |
bench "rescue for word" do | |
try do | |
String.to_integer(@word) | |
rescue | |
_ in ArgumentError -> @word | |
end | |
end | |
bench "rescue for integer" do | |
try do | |
String.to_integer(@integer) | |
rescue | |
_ in ArgumentError -> @integer | |
end | |
end | |
defp numeric_string?(string) do | |
Regex.match?(~r/\A\d+\Z/, string) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results:
try
/rescue
wins by far. This surprised me coming from Ruby where exceptions are extremely expensive.I wondered if extracting the regex into a module attribute would speed up its parsing, but of course Elixir is compiled so the regex isn't parsed at runtime and it doesn't make any difference: