Rails components are slow?
It’s been said on the net that Rails’ components are slow - to the point of being unusable. However, this quick, and admittedly incomplete, test seems to indicate little difference for this simple example. Note that the example uses the compoentry.rb code I outlined in this post.
### simple controller
class BarController < ApplicationController
def initialize
@foo = 42
@bar = ‘forty-two’
end
def foo
render :text => @foo
end
def bar
render :text => @bar
end
def foobar
render :text => [@foo, @bar].inspect #=> [42, “forty-two”]
end
end
class BarController < ApplicationController
def initialize
@foo = 42
@bar = ‘forty-two’
end
def foo
render :text => @foo
end
def bar
render :text => @bar
end
def foobar
render :text => [@foo, @bar].inspect #=> [42, “forty-two”]
end
end
### benchmarking
cfp:~/src/ruby/componentry/componentry-0.0.0/sample/rails > ab -n 25 -c 4 http://localhost:3000/bar/foobar|grep ‘Requests’
Requests per second: 7.05 [#/sec] (mean)
cfp:~/src/ruby/componentry/componentry-0.0.0/sample/rails > ab -n 25 -c 4 http://localhost:3000/bar/foobar|grep ‘Requests’
Requests per second: 7.05 [#/sec] (mean)
### controller which uses the the BarController via components
class FooController < ApplicationController
def foobar
# get a handle on, and parameterize, a bar controller
bar_controller = component_for(:controller => ‘bar’) do
@foo = 42
@bar = ‘forty-two’
end
# call two actions on the bar controller, reusing the entire
# model+view+controller
foo = bar_controller.content_for :action => ‘foo’
bar = bar_controller.content_for :action => ‘bar’
render :text => [foo, bar].inspect #=> [42, “forty-two”]
end
end
class FooController < ApplicationController
def foobar
# get a handle on, and parameterize, a bar controller
bar_controller = component_for(:controller => ‘bar’) do
@foo = 42
@bar = ‘forty-two’
end
# call two actions on the bar controller, reusing the entire
# model+view+controller
foo = bar_controller.content_for :action => ‘foo’
bar = bar_controller.content_for :action => ‘bar’
render :text => [foo, bar].inspect #=> [42, “forty-two”]
end
end
### benchmarking
cfp:~/src/ruby/componentry/componentry-0.0.0/sample/rails > ab -n 25 -c 4 http://localhost:3000/foo/foobar|grep ‘Requests’
Requests per second: 6.79 [#/sec] (mean)
cfp:~/src/ruby/componentry/componentry-0.0.0/sample/rails > ab -n 25 -c 4 http://localhost:3000/foo/foobar|grep ‘Requests’
Requests per second: 6.79 [#/sec] (mean)
So, in my mind, this seems to at least suggest that the above two requests, one with and one without components, are essentially the same. My reading of the rails source doesn’t show any significant work being done when components are used, many objects are dup’d when possible, so this makes sense to me.
Do you have code showing that they are significantly slower? If so drop me a line at ara[dot]t[dot]howard[at]gmail[dot]com.