Reputation: 37319
In my Rails application I need to query a binary file database on each page load. The query is read only. The file size is 1.4 MB. I have two questions:
1) Does it make sense to cache the File
object in a class variable?
def some_controller_action
@@file ||= File.open(filename, 'rb')
# binary search in @@file
end
2) Will the cached object be shared across different requests in the same rails process?
Upvotes: 3
Views: 1304
Reputation: 21690
If you use a constant in your class, aka
FILE = File.read(filename, 'rb').read
so it gets evaluated at application load time. The fork will happen afterwards, so it will be in the shared memory.
Upvotes: 5
Reputation: 25757
It does make sense. The limitation of this, however, is that if you spawn multiple procsesses for your app, each process will have to cache the 1.4 MB. So the answer to your second question is yes but it will not be shared across multiple processes.
Upvotes: 2