package com.mitchellbosecke.benchmark;

import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.mitchellbosecke.benchmark.io.CharStream;
import com.mitchellbosecke.benchmark.model.Stock;
import freemarker.template.TemplateException;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.io.IOException;
import java.util.Map;

public class Enjoy extends BaseBenchmark {

	private Map<?, ?> data;

	Engine engine;

	@Setup
	public void setup() throws IOException {
		// 配置快速模式，使用动态编译去除 java.lang.reflect.Method.invoke()，性能提升 13%
		Engine.setFastMode(true);
		// 配置从 class path 与 jar 包中读取模板文件
		engine = Engine.use().setToClassPathSourceFactory();

		// 获取渲染模板时用到的数据，类型为 JDK 的 Map 或其子类，本示例使用 Map 的子类 Kv
		data = Kv.by("items", Stock.dummyItems());
	}

	@Benchmark
	public void benchmark(Blackhole blackhole) throws TemplateException, IOException {
		Template template = engine.getTemplate("/templates/stocks.jfinal.html");
		template.render(data,new CharStream("UTF-8"));
		blackhole.consume(1);
	}
	public static void main(String[] args) throws RunnerException {

		Options opt = new
				OptionsBuilder()
				.include(Enjoy.class.getSimpleName()).forks(0)
				.build();
		new Runner(opt).run();
	}
}

