RubyMotion应该执行自动内存管理:
RubyMotion提供自动内存管理;您不需要回收未使用的对象。
但是,当循环读取大文件时,我遇到了巨大的内存泄漏:每秒数百MB / s,就好像从未释放我的读取缓冲区一样。
如果我release
在每个循环的读取缓冲区中使用泄漏,则泄漏通常会消失。问题是,release
循环结束后会使应用程序崩溃。
def readBigBinaryFile(file)
# PURE RUBY WOULD BE
# source=File.open(file,'r')
source =NSFileHandle.fileHandleForReadingAtPath(file)
buffer_size=4096
offset=0
size=File.size(file)
while ( offset + buffer_size ) <= size
# PURE RUBY WOULD BE
# source.seek(offset)
# abuffer = source.read( buffer_size )
# abuffer=abuffer.to_s
source.seekToFileOffset(offset)
abuffer = source.readDataOfLength(buffer_size)
offset+=buffer_size
@dataPointer ||= Pointer.new(:uchar,4)
abuffer.getBytes(@dataPointer, length: 4)
# memory leaks very rapidly in GBs if we don't release the buffer…
# but this relase action will make the application crash once the doSomething lookp is finished
abuffer.release
end
source.closeFile
return false
end
循环是:
x=0
while x < 10000
my_scan_binary_instance=Scan_binary.new() result=my_scan_binary_instance.readBigBinaryFile(NSBundle.mainBundle.pathForResource("sample1MBfile", ofType:"img"))
puts result.to_s
x+=1
end
puts "if we have used 'abuffer.release', we are going to crash now"
我测试了纯Ruby实现,完全没有内存泄漏,也不需要发布调用。
我发现了“如何在for循环中加载大型pickle文件时如何防止内存泄漏? ”有关Python循环中的内存泄漏,但是inabuffer=nil
开头的公认解决方案无效。while block
readBigBinaryFile
这是RubyMotion的自动内存管理中的错误,还是预期的?最重要的是,如何在不增加RubyMotion应用程序的内存使用的情况下循环读取大文件?
尝试将循环主体包裹在中autorelease_pool do ... end
。这将导致自动释放的对象在每个循环中被释放。在循环结束时分配nil
给abuffer
,将可以释放缓冲存储器,因为将不再有对其的引用。
while ( offset + buffer_size ) <= size
autorelease_pool do
source.seekToFileOffset(offset)
abuffer = source.readDataOfLength(buffer_size)
offset+=buffer_size
@dataPointer ||= Pointer.new(:uchar,4)
abuffer.getBytes(@dataPointer, length: 4)
abuffer = nil
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句