Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not necessary require(s) matter?

Tags:

ruby

require

I want to be able to have one ruby file that can require all the common dependencies, so that other files can just have one require on this shared file.for example; I have foo.rb and bar.rb and allrequires.rb. I want to have the line require "allrequires.rb" in both foo.rb and bar.rb, but bar.rb doesn't need all the requires.

Does it matter if I use require in .rb file that do not really require that file? Could it have an impact on performance maybe?

I am currently on ruby 1.8.7 (2010-08-16 patchlevel 302) [i386-mingw32]

Update

It looks like it is not the best idea to 'share'/use all requires in both .rb files. What would be solution to that?

Right now I can think of using file name in a condition.

like image 714
Radek Avatar asked Mar 04 '26 10:03

Radek


2 Answers

There's two main performance penalties:

  1. The time taken to do the require itself. In Ruby 1.9.1 and Ruby 1.9.2, the time taken to do all the requires had worse than linear scalability - if you doubled the number of requires, it took you more than twice as long - I think it took you four times as long.
  2. The time taken to execute the code in the file being required. If you have code like the following, then executing the code will take a non-trivial amount of time.
class MyClass
  MY_CONSTANT = File.read("data.txt")
end
like image 129
Andrew Grimm Avatar answered Mar 08 '26 12:03

Andrew Grimm


Another approach of conditional requiring, the following script gives no error on the JSON parser because it is named require1.rb, in scripts that have no name like require1.rb of script2.rb the gem isn't required

require 'json' if "require1.rb, script2.rb"[File.basename(__FILE__)]

p File.basename(__FILE__)

text = '[{ "name" : "car", "status": "good"}, { "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"},
  {"noname":"", "status" : "worse"}
]' 
data = JSON.parse(text) 

p data.collect { |item| item['name'] } 

EDIT: here a version that uses an array

["require1.rb","script1.rb"].find{|script|require 'json' if script===File.basename(__FILE__)}
like image 36
peter Avatar answered Mar 08 '26 10:03

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!