Skip to content

Instantly share code, notes, and snippets.

@vgarro
Created April 6, 2017 22:30
Show Gist options
  • Save vgarro/6d47739bd8cfc5bb7b519fcc8dd7b5ab to your computer and use it in GitHub Desktop.
Save vgarro/6d47739bd8cfc5bb7b519fcc8dd7b5ab to your computer and use it in GitHub Desktop.
Accessing ENV variables from ENV is slower than a constant in Ruby
class TestClass
def test
var = ENV['TEST_VAR']
var == 1
end
end
require 'benchmark'
Benchmark.bm do |x|
x.report { 1000000.times { TestClass.new.test } }
end
=> [#<Benchmark::Tms:0x007fe26c956810 @label="", @real=0.6151940660020045, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.6100000000000001, @total=0.6100000000000001>]
=> [#<Benchmark::Tms:0x007f803b02e258 @label="", @real=0.6114436259995273, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.6000000000000001, @total=0.6000000000000001>]
=> [#<Benchmark::Tms:0x007ffba2961f18 @label="", @real=0.6205215830013913, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.6100000000000001, @total=0.6100000000000001>]
module MyModule
ENV_VALUE = ENV['TEST_VAR']
class TestClass
def test
var = MyModule::ENV_VALUE
var == 1
end
end
end
require 'benchmark'
Benchmark.bm do |x|
x.report { 1000000.times { MyModule::TestClass.new.test } }
end
=> [#<Benchmark::Tms:0x007f893b8ced78 @label="", @real=0.25701763500183006, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.26, @total=0.26>]
=> [#<Benchmark::Tms:0x007f9672890160 @label="", @real=0.2614059769985033, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.26, @total=0.26>]
=> [#<Benchmark::Tms:0x007fc2031bb7b0 @label="", @real=0.25079641200136393, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.25, @total=0.25>]
# Just by adding one more zero (1 million to 10 million) times on both, we get almost 3 seconds difference
=> [#<Benchmark::Tms:0x007fde1a0d7938 @label="", @real=5.9996224630012875, @cstime=0.0, @cutime=0.0, @stime=0.019999999999999997, @utime=5.96, @total=5.9799999999999995>]
vs
=> [#<Benchmark::Tms:0x007fde1b0aed98 @label="", @real=2.5135619059983583, @cstime=0.0, @cutime=0.0, @stime=0.020000000000000004, @utime=2.4799999999999995, @total=2.4999999999999996>]
@crojasaragonez
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment