Created
April 5, 2012 13:36
-
-
Save johanb/2311073 to your computer and use it in GitHub Desktop.
Just zipping up some photos.. this leaks memory. How can I optimize this routine ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| photos.each do |photo| | |
| path = photo.photo.path | |
| file_path = zip_path + "/" + path | |
| FileUtils.mkdir_p(File.dirname(file_path)) | |
| File.open(file_path, 'wb') do |file| | |
| file.write photo.photo.file.read | |
| file.close # shouldn't make a difference | |
| end | |
| # FWIW, this doesn't make a difference | |
| # file = File.open(file_path, 'wb') | |
| # file.write photo.photo.file.read | |
| # file.close | |
| end | |
| system("cd #{temp_dir} && zip #{zip_path} -r #{zip_name}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This seem sot be my solution of avoiding a huge amount of memory usage. (Thanks to [hanke](http://twitter.com/hanke) & [alloy](http://twitter.com/alloy) ) | |
| FileUtils.mkdir_p(zip_path) | |
| photos.each do |photo| | |
| url = photo.photo_url | |
| path = photos.photo.path | |
| system("cd #{zip_path} && curl -L #{url} -o #{path} --create-dirs") | |
| end | |
| system("cd #{temp_dir} && zip #{zip_path} -r #{zip_name}") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This was my initial attempt which was altered transformed to what can be seen in Downloading in Ruby Zipping Shelled Out.rb | |
| Zip::ZipOutputStream.open(zip_path) do |zos| | |
| photos.each do |photo| | |
| zos.put_next_entry(photo.photo.path) | |
| zos.write photo.photo.file.read | |
| end | |
| end |
Author
Just a note to the last line here: It only prevents GC'ing of the downloaded file body because there's a reference chain to the file. A clear method would be nice, or similar.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
photo.photo.file.readcall.photo.photo.file.readcall comes from this file in CarrierWave Fogphoto.photo.file.readcall caches every single file read. Which prevents GC.