简体   繁体   English

如何在 Android 的 Renderscript 中释放 memory?

[英]How to release memory in Renderscript in Android?

Profiler in Android Studio shows that my Renderscript app has memory leak in Graphics memory. Android Studio 中的分析器显示我的 Renderscript 应用程序在图形 memory 中存在 memory 泄漏。 I wrote some test code and successfully reproduce the problem, but I don't know how to solve it.我写了一些测试代码并成功重现了问题,但我不知道如何解决它。

Renderscript code渲染脚本代码

void memoryTest(rs_allocation output) {
    rs_allocation tmp;
    for(int i = 0; i < 10; i++) {
        tmp = rsCreateAllocation_char(1000, 1000);
    }
}

Kotlin code Kotlin 代码

val rs: RenderScript = RenderScript.create(this)
while (true) {
    val script = ScriptC_singlesource(rs)
    val outputAllocation = Allocation.createTyped(rs, Type.createXY(rs, Element.I16(rs), 1000, 1000))
    script.invoke_memoryTest(outputAllocation)
    outputAllocation.destroy()
    script.destroy()
}

Memory usage Memory 用法内存使用情况 I ended the run at 15 seconds, that's why memory went down.我在 15 秒时结束了运行,这就是 memory 下降的原因。

I tried free(tmp) , delete tmp , delete(tmp) , all results in compile error.我试过free(tmp)delete tmpdelete(tmp) ,都导致编译错误。 I want to know how to free up the memory of rs_allocation created inside Renderscript.我想知道如何释放在 Renderscript 中创建的 rs_allocation 的rs_allocation

Edit编辑

I tried rsClearObject(rs_allocation*) , the Renderscript became我尝试rsClearObject(rs_allocation*) ,Renderscript 变成了

void memoryTest(rs_allocation output) {
    rs_allocation tmp;
    for(int i = 0; i < 10; i++) {
        rsClearObject(&tmp);
        tmp = rsCreateAllocation_char(1000, 1000);
    }
}

It didn't solve the problem.它没有解决问题。 The memory usage remains the same. memory 用法保持不变。 It doesn't seem to have any effect.它似乎没有任何效果。

Finally solved it.终于解决了。 You just need to use another variable inside the loop to create the rs_allocation , and then pass it to the outside variable.您只需要在循环内使用另一个变量来创建rs_allocation ,然后将其传递给外部变量。

void memoryTest(rs_allocation output) {
    rs_allocation tmp;
    for(int i = 0; i < 10; i++) {
        rs_allocation tmp2 = rsCreateAllocation_char(1000, 1000);
        tmp = tmp2;

        //In my case tmp is a global variable used to pass value to kernel functions,
        //so it has to be outside.
        somefunctionThatUseTmp();
    }
}

I can't explain why this works, it defies my understanding of how pointers work in C.我无法解释为什么会这样,它违背了我对指针在 C 中如何工作的理解。

没有内存泄漏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM