Skip to content

Instantly share code, notes, and snippets.

@samflores
Last active November 16, 2017 18:22
Show Gist options
  • Save samflores/a9c5e37843e1b52869dacf56f33e3bc4 to your computer and use it in GitHub Desktop.
Save samflores/a9c5e37843e1b52869dacf56f33e3bc4 to your computer and use it in GitHub Desktop.
import javax.script.*;
import java.util.*;
class Expression {
private Long id;
private String name;
private String expression;
private String[] parameters;
private Compilable engine;
public Expression(Long id, String name, String[] parameters, String expression) {
this.id = id;
this.name = name;
this.parameters = parameters;
this.expression = expression;
}
public String getName() { return name; }
public String invocation(String... args) {
return String.format("%s(%s)",
name,
String.join(", ", args)
);
}
public String declaration() {
return String.format("function(%s) { return %s; }",
String.join(", ", parameters),
expression
);
}
}
public class Executioner {
private static final int ITERATIONS = 10000;
private final ScriptEngineManager manager = new ScriptEngineManager();
private final ScriptEngine engine;
public Expression[] database;
public Executioner() {
engine = manager.getEngineByName("nashorn");
database = new Expression [] {
new Expression(1L, "media", new String [] { "a", "b" }, "(a + b) / 2.0"),
new Expression(2L, "resultado", new String [] { "x", "y" }, "media(x, y) + 20"),
};
}
public Object run(Expression expression, String... args) throws ScriptException {
return engine.eval(expression.invocation(args));
}
private void compileDatabase() throws ScriptException {
for (Expression expression : database) {
engine.put(
expression.getName(),
((Compilable)engine).compile(expression.declaration()).eval()
);
}
}
public static void main(String[] args) throws ScriptException {
Executioner executioner = new Executioner();
double duration = System.nanoTime();
executioner.compileDatabase();
duration = (System.nanoTime() - duration) / 1000000;
System.out.printf("Compilation\n");
System.out.printf("%10.3fms\n", duration);
System.out.printf("%10.3fms/i\n\n", duration / executioner.database.length);
Expression expression = executioner.database[1];
String[] a = new String[ITERATIONS];
String[] b = new String[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++) {
a[i] = String.valueOf(Math.random() * 5 + 3);
b[i] = String.valueOf(Math.random() * 5 + 3);
}
duration = System.nanoTime();
for (int i = 0; i < ITERATIONS; i++) {
Object result = executioner.run(expression, a[i], b[i]);
}
duration = (System.nanoTime() - duration) / 1000000;
System.out.printf("Execution\n");
System.out.printf("%10.3fms\n", duration);
System.out.printf("%10.3fms/i\n", duration / ITERATIONS);
}
}
@samflores
Copy link
Author

Na minha máquina:

Compilation
   191.580ms
    95.790ms/i

Execution
 14126.092ms
     1.413ms/I

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment