3

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?

1
  • How do you query the binary file? Commented Jun 4, 2012 at 9:40

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Good idea, thank you. My only concern here is that it would read the file on each app initialization (rails c, in tests etc). What I wanted is a lazy loading of the file, only when it's first accessed.
You can't have both the cake and eat it (it's a lie anyway), but you could make a method that uses the constant in production mode and lazy-loads otherwise.
Yeah, good point about the cakes. I think the idea is getting a bit over-architected. Thanks, anyway.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.