From: John Joyce Date: 2007-09-21T11:16:39+09:00 Subject: Re: I am new to Ruby and I could use some expert advice as to how I can make this code run faster. On Sep 20, 2007, at 8:50 PM, Brian Adkins wrote: > On Sep 20, 6:02 pm, Ruby Maniac wrote: >> I am new to Ruby and I could use some expert advice as to how I can >> make this code run faster. > > Write a C extension. Seriously, Ruby is pretty darn slow at iterating > over each byte of a file. The I/O is reasonable, but the byte > iteration is terrible. You might get a small speedup by using > File#read instead of File#each_byte: > > while (buffer = f.read(BUF_SIZE)) > buffer.each_byte {|b| ... } > end > > I got about a 5% speedup using an 8K buffer. > > You also may want to consider the idiom: > > File.open(filename) do |f| > ... > end > > This will automatically close the file at the end of the block. > >> def scramble(fname) >> f = File.new(fname, "rb") >> _fname = fname + ".scrambled" >> begin >> File.exist?(_fname) if File.delete(_fname) > > You may want to double check the previous line. > >> rescue >> end >> ff = File.new(_fname, "wb+") >> for l in f >> l.each_byte{|c| ff.write((c | 0x80).chr) } > > So you don't need to get the original file data back, right? If you > do, you may want to use xor instead, and if you don't, then why not > just write zeros? > >> end >> f.close() >> ff.close() >> end > > > Benchmark it so you can find the bottlenecks.