Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmarking performance of slicing text in different formats/ways
# 1024 bytes long string
string = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus iaculis erat. Cras orci enim, vulputate a elementum at, rutrum pulvinar sem. Donec gravida quam at lectus sagittis, eu facilisis felis scelerisque. Nulla quis leo quis ipsum sollicitudin pharetra. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec bibendum porttitor hendrerit. In hac habitasse platea dictumst.
Sed blandit massa ut lorem accumsan, ut suscipit erat aliquet. Ut vulputate sit amet ligula non auctor. Nullam pharetra vestibulum velit, lobortis ultrices ante blandit quis. Curabitur gravida fringilla enim non pulvinar. Vestibulum facilisis turpis ipsum, ac tempor magna varius at. Cras pulvinar mi in varius mattis. Curabitur viverra nibh est, eu consectetur magna euismod eget. Suspendisse potenti. Vestibulum hendrerit auctor dui id imperdiet. Quisque congue enim non eros lobortis, rhoncus aliquam lacus eleifend. Nam et malesuada mauris, et semper velit. Aenean volutpat cursus ornare. Cras aliquam hendrerit est nullam.
"""
charlist = String.to_charlist(string)
Benchee.run(%{
"string" => fn ->
String.slice(string, 500, 501)
end,
"charlist" => fn ->
Enum.slice(charlist, 500, 501)
end,
"binary" => fn ->
binary_part(string, 500, 1)
end
})
Operating System: macOS
CPU Information: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
Number of Available Cores: 4
Available memory: 16 GB
Elixir 1.10.2
Erlang 22.2.8
Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 0 ns
parallel: 1
inputs: none specified
Estimated total run time: 21 s
Benchmarking binary...
Benchmarking charlist...
Benchmarking string...
Name ips average deviation median 99th %
binary 6295.14 K 0.159 μs ±774.35% 0 μs 1 μs
charlist 134.25 K 7.45 μs ±432.53% 7 μs 15 μs
string 17.35 K 57.65 μs ±37.55% 55 μs 107 μs
Comparison:
binary 6295.14 K
charlist 134.25 K - 46.89x slower +7.29 μs
string 17.35 K - 362.94x slower +57.49 μs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment