Skip to content

Instantly share code, notes, and snippets.

@areina
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save areina/9233841 to your computer and use it in GitHub Desktop.
Save areina/9233841 to your computer and use it in GitHub Desktop.
Benchmark about rescue exceptions
require 'benchmark/ips'
Benchmark.ips do |bm|
path = "/tmp/unknown_file.unknown_ext"
bm.report("using rescue") do
begin
File.read(path)
rescue
"file doesn't exist"
end
end
bm.report("checking if file exists") do
if File.exists?(path)
File.read(path)
else
"file doesn't exist"
end
end
end
require 'benchmark'
iterations = 1_000_000
Benchmark.bm(27) do |bm|
path = "/tmp/unknown_file.unknown_ext"
bm.report("using rescue") do
iterations.times do
begin
File.read(path)
rescue
"file doesn't exist"
end
end
end
bm.report("checking if file exists") do
iterations.times do
if File.exists?(path)
File.read(path)
else
"file doesn't exist"
end
end
end
end
user system total real
using rescue 9.870000 1.490000 11.360000 ( 11.513433)
checking if file exists 0.440000 0.660000 1.100000 ( 1.102379)
Calculating -------------------------------------
using rescue 7454 i/100ms
checking if file exists
45063 i/100ms
-------------------------------------------------
using rescue 85105.1 (±1.6%) i/s - 432332 in 5.081270s
checking if file exists
807410.8 (±2.9%) i/s - 4055670 in 5.027569s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment