Added CSS/XPath Parser.parse_with_cache

This method parses and caches ASTs using Oga::LRU. Currently the default
of 1024 keys is used.

See #71 for more information.
This commit is contained in:
Yorick Peterse 2015-03-23 00:22:59 +01:00
parent 67d7d9af88
commit 2c4e490614
6 changed files with 94 additions and 2 deletions

View File

@ -3,7 +3,13 @@ require_relative '../../benchmark_helper'
css = 'foo bar bar.some_class element#with_id[title="Foo"]'
Benchmark.ips do |bench|
bench.report 'CSS' do
bench.report 'without cache' do
Oga::CSS::Parser.new(css).parse
end
bench.report 'with cache' do
Oga::CSS::Parser.parse_with_cache(css)
end
bench.compare!
end

View File

@ -3,7 +3,13 @@ require_relative '../../benchmark_helper'
xpath = '/wikimedia/projects/project[@name="Wikipedia"]/editions/edition/text()'
Benchmark.ips do |bench|
bench.report 'Wikipedia example' do
bench.report 'without cache' do
Oga::XPath::Parser.new(xpath).parse
end
bench.report 'with cache' do
Oga::XPath::Parser.parse_with_cache(xpath)
end
bench.compare!
end

View File

@ -310,6 +310,19 @@ even
%inner
{
##
# @return [Oga::LRU]
#
CACHE = LRU.new
##
# @param [String] data
# @return [AST::Node]
#
def self.parse_with_cache(data)
return CACHE.get_or_set(data) { new(data).parse }
end
##
# @param [String] data The input to parse.
#

View File

@ -223,6 +223,19 @@ variable
%inner
{
##
# @return [Oga::LRU]
#
CACHE = LRU.new
##
# @param [String] data
# @return [AST::Node]
#
def self.parse_with_cache(data)
return CACHE.get_or_set(data) { new(data).parse }
end
##
# @param [String] data The input to parse.
#

View File

@ -0,0 +1,27 @@
require 'spec_helper'
describe Oga::CSS::Parser do
describe 'parse_with_cache' do
after do
described_class::CACHE.clear
end
it 'parses an expression' do
described_class.parse_with_cache('foo')
.should == s(:axis, 'descendant', s(:test, nil, 'foo'))
end
it 'caches an expression after parsing it' do
described_class.any_instance
.should_receive(:parse)
.once
.and_call_original
described_class.parse_with_cache('foo')
.should == s(:axis, 'descendant', s(:test, nil, 'foo'))
described_class.parse_with_cache('foo')
.should == s(:axis, 'descendant', s(:test, nil, 'foo'))
end
end
end

View File

@ -0,0 +1,27 @@
require 'spec_helper'
describe Oga::XPath::Parser do
describe 'parse_with_cache' do
after do
described_class::CACHE.clear
end
it 'parses an expression' do
described_class.parse_with_cache('foo')
.should == s(:axis, 'child', s(:test, nil, 'foo'))
end
it 'caches an expression after parsing it' do
described_class.any_instance
.should_receive(:parse)
.once
.and_call_original
described_class.parse_with_cache('foo')
.should == s(:axis, 'child', s(:test, nil, 'foo'))
described_class.parse_with_cache('foo')
.should == s(:axis, 'child', s(:test, nil, 'foo'))
end
end
end