Skip to content

Commit f503e53

Browse files
committed
auto merge of #7608 : glinscott/rust/json_perf, r=pcwalton
Avoids the overhead of read_char for every character. Benchmark reading example.json 10 times from https://code.google.com/p/rapidjson/wiki/Performance Before: 2.55s After: 0.16s Regression testing is already done by isrustfastyet.
2 parents f7b293b + 149c976 commit f503e53

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

src/libextra/json.rs

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -481,22 +481,30 @@ pub fn to_pretty_str(json: &Json) -> ~str {
481481
io::with_str_writer(|wr| to_pretty_writer(wr, json))
482482
}
483483

484+
static BUF_SIZE : uint = 64000;
485+
484486
#[allow(missing_doc)]
485487
pub struct Parser {
486488
priv rdr: @io::Reader,
489+
priv buf: ~[char],
490+
priv buf_idx: uint,
487491
priv ch: char,
488492
priv line: uint,
489493
priv col: uint,
490494
}
491495

492496
/// Decode a json value from an io::reader
493497
pub fn Parser(rdr: @io::Reader) -> Parser {
494-
Parser {
498+
let mut p = Parser {
495499
rdr: rdr,
496-
ch: rdr.read_char(),
500+
buf: rdr.read_chars(BUF_SIZE),
501+
buf_idx: 0,
502+
ch: 0 as char,
497503
line: 1,
498-
col: 1,
499-
}
504+
col: 0,
505+
};
506+
p.bump();
507+
p
500508
}
501509

502510
impl Parser {
@@ -521,13 +529,26 @@ impl Parser {
521529
fn eof(&self) -> bool { self.ch == -1 as char }
522530

523531
fn bump(&mut self) {
524-
self.ch = self.rdr.read_char();
532+
if self.eof() {
533+
return;
534+
}
535+
536+
self.col += 1u;
537+
538+
if self.buf_idx >= self.buf.len() {
539+
self.buf = self.rdr.read_chars(BUF_SIZE);
540+
if self.buf.len() == 0 {
541+
self.ch = -1 as char;
542+
return;
543+
}
544+
self.buf_idx = 0;
545+
}
546+
self.ch = self.buf[self.buf_idx];
547+
self.buf_idx += 1;
525548

526549
if self.ch == '\n' {
527550
self.line += 1u;
528551
self.col = 1u;
529-
} else {
530-
self.col += 1u;
531552
}
532553
}
533554

src/libstd/char.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ pub fn is_uppercase(c: char) -> bool { general_category::Lu(c) }
8282
///
8383
#[inline]
8484
pub fn is_whitespace(c: char) -> bool {
85-
('\x09' <= c && c <= '\x0d')
85+
c == ' '
86+
|| ('\x09' <= c && c <= '\x0d')
8687
|| general_category::Zs(c)
8788
|| general_category::Zl(c)
8889
|| general_category::Zp(c)

0 commit comments

Comments
 (0)