#running in to memory leak with loop calling js function from rustland (rusty_v8)

9 messages · Page 1 of 1 (latest)

muted grove
#

Here I want to be able to run a js function that is looped over and over, it keeps making v8 values
I can't exactly wrap my head around how to clean out the values that aren't being used after each loop

index.js:

let i = 0;
function tick() {
    i++;
    return "loop "+i;
}

main.rs:

use std::fs;
use v8::{self};

fn main() {
    // init v8
    let platform = v8::new_default_platform(0, false).make_shared();
    v8::V8::initialize_platform(platform);
    v8::V8::initialize();

    let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
    let handle_scope = &mut v8::HandleScope::new(isolate);
    let context = v8::Context::new(handle_scope);
    let context_scope = &mut v8::ContextScope::new(handle_scope, context);

    { //gets the js from a file
        let mut scope = v8::TryCatch::new(context_scope);
        let js = fs::read_to_string(format!("./index.js")).unwrap();
        let rogger = v8::String::new(&mut scope, &js).unwrap();
        let script = v8::Script::compile(&mut scope, rogger, None).unwrap();
        script.run(&mut scope).unwrap();
    };

    let tick_funk = { //get the "tick" function form js
        let mut scope = v8::TryCatch::new(context_scope);
        let key = v8::String::new(&mut scope, "tick").unwrap();
        let tick_funk = context.global(&mut scope).get(&mut scope, key.into()).unwrap();

        let tick_object: v8::Local<v8::Object> = tick_funk.to_object(&mut scope).unwrap();
        v8::Local::<v8::Function>::try_from(tick_object).unwrap()
    };

    loop{
        //run the "tick" function
        let mut scope = v8::TryCatch::new(context_scope);
        let globe = context.global(&mut scope);

        let targ: v8::Local<v8::Value> = v8::Number::new(&mut scope, 0.0).into();

        let ftick_result = tick_funk
            .call(&mut scope, globe.into(), &[targ])
            .unwrap();
        dbg!(ftick_result.to_rust_string_lossy(&mut scope));
    };
}
#

funny enough I asked gpt for a fix, they kept telling me to use isolate.low_memory_notification() which is a problem because isolate is being borrowed
which is oof

junior stirrup
#

which values are not getting cleaned up?

#

also how much memory is leaked?

#

GPT is not wrong - calling isolate.low_memory_notification() will cause V8 to perform garbage collection

muted grove
#

globe, targ I don't think are being clears
it's leaking a mb a second

junior stirrup
#

they should be cleared though, try catch scope is dropped at the end of the loop body so that should mark these variables as GCable

#

did you try with that isolate.low_memory_notification()?

#

I'm also surprised that this program compiles - the let tick_funk = looks suspicious - you shouldn't be able to return a local from that block because the scope you use to acquire it is getting dropped.