Skip to content

Commit

Permalink
(test) improve bench
Browse files Browse the repository at this point in the history
  • Loading branch information
sunng87 committed Jun 30, 2016
1 parent c87aafc commit 0fae391
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 40 deletions.
51 changes: 26 additions & 25 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,39 @@ extern crate handlebars;
extern crate rustc_serialize as serialize;
extern crate test;

use std::io::prelude::*;
use std::io::Result;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;

use handlebars::{Handlebars, Template};
use serialize::json::{Json, ToJson};

fn load_template_source(name: &str) -> Result<String> {
let path = Path::new(name);
static SOURCE: &'static str = "<html>
<head>
<title>{{year}}</title>
</head>
<body>
<h1>CSL {{year}}</h1>
<ul>
{{#each teams}}
<li class=\"{{#if @first}}champion{{/if}}\">
<b>{{name}}</b>: {{score}}
</li>
{{/each}}
</ul>
</body>
</html>";

let mut file = try!(File::open(&path));
let mut buf = String::new();
try!(file.read_to_string(&mut buf));
Ok(buf)
}

fn make_data () -> BTreeMap<String, Json> {
fn make_data() -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();

data.insert("year".to_string(), "2015".to_json());

let mut teams = Vec::new();

for v in vec![("Jiangsu", 43u16), ("Beijing", 27u16), ("Guangzhou", 22u16), ("Shandong", 12u16)].iter() {
for v in vec![("Jiangsu", 43u16),
("Beijing", 27u16),
("Guangzhou", 22u16),
("Shandong", 12u16)]
.iter() {
let (name, score) = *v;
let mut t = BTreeMap::new();
t.insert("name".to_string(), name.to_json());
Expand All @@ -42,22 +49,16 @@ fn make_data () -> BTreeMap<String, Json> {

#[bench]
fn parse_template(b: &mut test::Bencher) {
let source = load_template_source("./benches/template.hbs").ok().unwrap();
b.iter(|| {
Template::compile(source.clone()).ok().unwrap()
});
b.iter(|| Template::compile(SOURCE.clone()).ok().unwrap());
}

#[bench]
fn render_template(b: &mut test::Bencher) {
let source = load_template_source("./benches/template.hbs").ok().unwrap();

let mut handlebars = Handlebars::new();
handlebars.register_template_string("table", source)
.ok().expect("Invalid template format");
handlebars.register_template_string("table", SOURCE.to_string())
.ok()
.expect("Invalid template format");

let data = make_data();
b.iter(|| {
handlebars.render("table", &data).ok().unwrap()
})
b.iter(|| handlebars.render("table", &data).ok().unwrap())
}
15 changes: 0 additions & 15 deletions benches/template.hbs

This file was deleted.

0 comments on commit 0fae391

Please sign in to comment.