0

I am using code like this:

JS_EvaluateScript(context, global,"go_back('blabla')", 17, "", 1, &R);

to call go_back(), which is already in the context. But this is extremely slow, and I think because the string have to be compiled each time.

I try to find the way to call the same piece of code many times in a fast way, without recompilation, or some object creation each time. But Mozilla docs and sources are not organized that way, there is only a reference, and you need to know every function before you can make any choice.

So any hints? What would be the best practice for this?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 1
    You could use the XDR calls to serialize your compiled bytecodes (a JSScript object) to a file. When you need to execute the bytecodes again, create a JSScript object by reading from the saved image. That way you avoid the re-compilation. But a simple script like yours should not take too long to compile! – JavaMan Dec 01 '13 at 13:02

1 Answers1

0
JSFunction * FUNC = 0;

static JSBool my_native(JSContext *cx, uintN argc, jsval *vp) {
    jsval R = JSVAL_FALSE;
    if (FUNC == 0) {
        const char *ARGS[1] = {"s"}, *src = "go_back(s)";
        FUNC = JS_CompileFunction(cx, 0, 0, 1, ARGS, src, 10, "", 0);
    }
    JS_CallFunction(cx, 0, FUNC, 1, &R, &R);
    return JS_TRUE;
}

This is very fast (20 times in my example), compared to JS_EvaluateScript. Note that this code is very simplified, you still need to pass the string argument somehow. (I am not sure myself how to do that.) And you may need to JS_ReportPendingException() as go_back() can sometimes fail.

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
exebook
  • 32,014
  • 33
  • 141
  • 226