From: Eric Mahurin Date: 2008-02-05T08:07:52+09:00 Subject: Re: [QUIZ] Parsing JSON (#155) ------=_Part_8314_6373180.1202166478094 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Feb 1, 2008 7:55 AM, Ruby Quiz wrote: > In honor of that, this week's Ruby Quiz is to write a parser for JSON. Here is another solution of mine: http://pastie.caboo.se/147505 In this one, I just made a fast hand-built recursive-descent/LL(1) parser. This is the kind of parser that I'm trying to get my 'grammar' package to approach (using lots of optimizations). It uses no Regexp or ruby eval (both of which have compiled C to help speed). And yet, it is the fastest pure-ruby JSON parser we've seen (see the recursive descent line below): ch/s author/gem ---- ---------- - Pawel Radecki (RE, mismatch) 3214 Justin Ethier (RE lexer + ruby eval, fixed number parsing) 4054 Eric Mahurin (Grammar0, no lexer, no parser generation) 4078 Eric I (Treetop, unicode broken) 6534 oksteev (Treetop, mismatches in benchmark) 8313 Clifford Heath (Treetop, had to remove handling of "\/") 17320 Alexander Stedile (RE) 54586 Eric Mahurin (Grammar, no lexer, v0.5) 137989 Paolo Bonzini (RE) 166041 Thomas Link (RE lexer + ruby eval, ruby 1.9 results) 220289 json 223486 Eric Mahurin (Grammar, no lexer, unreleased) 224823 fjson (uses C extensions) 333368 Thomas Link & Paolo Bonzini (RE + eval, unicode broken) 388670 Eric Mahurin (hand-built recursive descent) 553081 Eric Mahurin (Grammar, no lexer, unreleased, w/ ruby2cext) 1522250 json (w/ C extensions) # # JSON hand-built recursive descent/LL(1) parser, by Eric Mahurin # require 'stringio' class JSONParser def parse(s) @next = (@io=StringIO.new(s)).getc ws value(out=[]) ws raise("EOF expected") if @next raise(out.inspect) unless out.length==1 out[0] end def error(expected, found) raise("expected #{expected}, found #{found ? ("'"<