我有一个程序可以产生模拟输入。该程序将用户输入文件的位置和文件以及扩展名。然后使用迭代将文件分解并将其放入数组中。优化红宝石阵列或哈希
def file_to_array(file)
empty = []
File.foreach("#{file}") do |line|
empty << line.to_s.split('')
end
return empty.flatten!
end
当程序运行时,它发送密钥到文本区经由win32ole
模拟输入。
经过5000个字符后,内存开销过大,程序开始变慢。越过5000个字符,它越慢。有没有一种方法可以优化?
- 编辑 -
require 'Benchmark'
def file_to_array(file)
empty = []
File.foreach(file) do |line|
empty << line.to_s.split('')
end
return empty.flatten!
end
def file_to_array_2(file)
File.read(file).split('')
end
file = 'xxx'
Benchmark.bm do |results|
results.report { print file_to_array(file) }
results.report { print file_to_array_2(file) }
end
user system total real
0.234000 0.000000 0.234000 ( 0.787020)
0.218000 0.000000 0.218000 ( 1.917185)
我难以置信 - 数组'empty'每个元素存储一个字符?你是否考虑过只存储文本,并使用'each_char'遍历它? (或者,根本不存储它,但将它留在...?) –
我写了一个基于@Aetherus的建议使用这种方法的替代方法,但是当我测试它时,内存开始被限制在大约7,000字符,从而程序开始放缓。我目前在这个代码片段中使用的方法减慢了大约5,000个字符。这是一个改进,但还不够。通过我所看到的优化,我确实设法将系统压力减半。你可以在这里查看完整的代码。 https://github.com/sinithwar/LazyProjects/blob/master/RubyTypingSim.rb –