gfx: Perform more aggressive caching in

`FontContext::get_layout_font_group_for_style()`.

There are several optimizations here:

* We make font families atoms, to allow for quicker comparisons.

* We precalculate an FNV hash of the relevant fields of the font style
  structure.

* When obtaining a platform font group, we first check pointer equality
  for the font style. If there's no match, we go to the FNV hash. Only
  if both caches miss do we construct and cache a font group. Note that
  individual fonts are *also* cached; thus there are two layers of
  caching here.

15% improvement in total layout thread time for Facebook Timeline.
This commit is contained in:
Patrick Walton 2015-03-18 21:06:02 -07:00
parent 6824bc9324
commit 750bbed2cb
14 changed files with 144 additions and 62 deletions

View file

@ -2,18 +2,18 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Token, Parser, DeclarationListParser, AtRuleParser, DeclarationParser};
use std::ascii::AsciiExt;
use stylesheets::CSSRule;
use properties::longhands::font_family::parse_one_family;
use computed_values::font_family::FontFamily;
use cssparser::{Token, Parser, DeclarationListParser, AtRuleParser, DeclarationParser};
use media_queries::Device;
use url::{Url, UrlParser};
use parser::{ParserContext, log_css_error};
use properties::longhands::font_family::parse_one_family;
use std::ascii::AsciiExt;
use string_cache::Atom;
use stylesheets::CSSRule;
use url::{Url, UrlParser};
pub fn iter_font_face_rules_inner<F>(rules: &[CSSRule], device: &Device,
callback: &F) where F: Fn(&str, &Source) {
pub fn iter_font_face_rules_inner<F>(rules: &[CSSRule], device: &Device, callback: &F)
where F: Fn(&Atom, &Source) {
for rule in rules.iter() {
match *rule {
CSSRule::Style(..) |
@ -34,7 +34,7 @@ pub fn iter_font_face_rules_inner<F>(rules: &[CSSRule], device: &Device,
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Source {
Url(UrlSource),
Local(String),
Local(Atom),
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -45,11 +45,10 @@ pub struct UrlSource {
#[derive(Debug, PartialEq, Eq)]
pub struct FontFaceRule {
pub family: String,
pub family: Atom,
pub sources: Vec<Source>,
}
pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
-> Result<FontFaceRule, ()> {
let mut family = None;
@ -83,7 +82,7 @@ pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
}
enum FontFaceDescriptorDeclaration {
Family(String),
Family(Atom),
Src(Vec<Source>),
}
@ -106,7 +105,8 @@ impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
fn parse_value(&self, name: &str, input: &mut Parser) -> Result<FontFaceDescriptorDeclaration, ()> {
match_ignore_ascii_case! { name,
"font-family" => {
Ok(FontFaceDescriptorDeclaration::Family(try!(parse_one_non_generic_family_name(input))))
Ok(FontFaceDescriptorDeclaration::Family(try!(
parse_one_non_generic_family_name(input))))
},
"src" => {
Ok(FontFaceDescriptorDeclaration::Src(try!(input.parse_comma_separated(|input| {
@ -118,9 +118,9 @@ impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
}
}
fn parse_one_non_generic_family_name(input: &mut Parser) -> Result<String, ()> {
fn parse_one_non_generic_family_name(input: &mut Parser) -> Result<Atom, ()> {
match parse_one_family(input) {
Ok(FontFamily::FamilyName(name)) => Ok(name),
Ok(FontFamily::FamilyName(name)) => Ok(name.clone()),
_ => Err(())
}
}

View file

@ -10,7 +10,6 @@ use log;
use stylesheets::Origin;
pub struct ParserContext<'a> {
pub base_url: &'a Url,
pub selector_context: SelectorParserContext,

View file

@ -8,10 +8,13 @@
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::default::Default;
use std::fmt;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use util::fnv::FnvHasher;
use util::logical_geometry::{WritingMode, LogicalMargin};
use util::geometry::Au;
use url::Url;
@ -1456,18 +1459,20 @@ pub mod longhands {
${new_style_struct("Font", is_inherited=True)}
<%self:longhand name="font-family">
use std::borrow::ToOwned;
use self::computed_value::FontFamily;
use std::borrow::ToOwned;
use string_cache::Atom;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub mod computed_value {
use cssparser::ToCss;
use string_cache::Atom;
use text_writer::{self, TextWriter};
#[derive(PartialEq, Eq, Clone)]
#[derive(PartialEq, Eq, Clone, Hash)]
pub enum FontFamily {
FamilyName(String),
FamilyName(Atom),
// Generic
// Serif,
// SansSerif,
@ -1476,16 +1481,17 @@ pub mod longhands {
// Monospace,
}
impl FontFamily {
#[inline]
pub fn name(&self) -> &str {
match *self {
FontFamily::FamilyName(ref name) => name,
FontFamily::FamilyName(ref name) => name.as_slice(),
}
}
}
impl ToCss for FontFamily {
fn to_css<W>(&self, dest: &mut W) -> text_writer::Result where W: TextWriter {
match self {
&FontFamily::FamilyName(ref name) => dest.write_str(&**name),
&FontFamily::FamilyName(ref name) => dest.write_str(name.as_slice()),
}
}
}
@ -1506,7 +1512,7 @@ pub mod longhands {
#[inline]
pub fn get_initial_value() -> computed_value::T {
vec![FontFamily::FamilyName("serif".to_owned())]
vec![FontFamily::FamilyName(Atom::from_slice("serif"))]
}
/// <family-name>#
/// <family-name> = <string> | [ <ident>+ ]
@ -1516,7 +1522,7 @@ pub mod longhands {
}
pub fn parse_one_family(input: &mut Parser) -> Result<FontFamily, ()> {
if let Ok(value) = input.try(|input| input.expect_string()) {
return Ok(FontFamily::FamilyName(value.into_owned()))
return Ok(FontFamily::FamilyName(Atom::from_slice(value.as_slice())))
}
let first_ident = try!(input.expect_ident());
// match_ignore_ascii_case! { first_ident,
@ -1532,7 +1538,7 @@ pub mod longhands {
value.push_str(" ");
value.push_str(&ident);
}
Ok(FontFamily::FamilyName(value))
Ok(FontFamily::FamilyName(Atom::from_slice(value.as_slice())))
}
</%self:longhand>
@ -1592,10 +1598,10 @@ pub mod longhands {
}
pub mod computed_value {
use std::fmt;
#[derive(PartialEq, Eq, Copy, Clone)]
#[derive(PartialEq, Eq, Copy, Clone, Hash)]
pub enum T {
% for weight in range(100, 901, 100):
Weight${weight},
Weight${weight} = ${weight},
% endfor
}
impl fmt::Debug for T {
@ -1608,6 +1614,7 @@ pub mod longhands {
}
}
impl T {
#[inline]
pub fn is_bold(self) -> bool {
match self {
T::Weight900 | T::Weight800 |
@ -4663,6 +4670,9 @@ pub mod style_structs {
% for longhand in style_struct.longhands:
pub ${longhand.ident}: longhands::${longhand.ident}::computed_value::T,
% endfor
% if style_struct.name == "Font":
pub hash: u64,
% endif
}
% endfor
}
@ -4836,6 +4846,9 @@ lazy_static! {
% for longhand in style_struct.longhands:
${longhand.ident}: longhands::${longhand.ident}::get_initial_value(),
% endfor
% if style_struct.name == "Font":
hash: 0,
% endif
}),
% endfor
shareable: true,
@ -4932,6 +4945,11 @@ fn cascade_with_cached_declarations(
}
}
if seen.get_font_style() || seen.get_font_weight() || seen.get_font_stretch() ||
seen.get_font_family() {
compute_font_hash(&mut *style_font.make_unique())
}
ComputedValues {
writing_mode: get_writing_mode(&*style_inheritedbox),
% for style_struct in STYLE_STRUCTS:
@ -5180,6 +5198,11 @@ pub fn cascade(viewport_size: Size2D<Au>,
context.root_font_size = context.font_size;
}
if seen.get_font_style() || seen.get_font_weight() || seen.get_font_stretch() ||
seen.get_font_family() {
compute_font_hash(&mut *style_font.make_unique())
}
(ComputedValues {
writing_mode: get_writing_mode(&*style_inheritedbox),
% for style_struct in STYLE_STRUCTS:
@ -5297,3 +5320,13 @@ pub fn longhands_from_shorthand(shorthand: &str) -> Option<Vec<String>> {
_ => None,
}
}
/// Corresponds to the fields in `gfx::font_template::FontTemplateDescriptor`.
fn compute_font_hash(font: &mut style_structs::Font) {
let mut hasher: FnvHasher = Default::default();
hasher.write_u16(font.font_weight as u16);
font.font_stretch.hash(&mut hasher);
font.font_family.hash(&mut hasher);
font.hash = hasher.finish()
}

View file

@ -318,8 +318,8 @@ pub fn iter_stylesheet_style_rules<F>(stylesheet: &Stylesheet, device: &media_qu
#[inline]
pub fn iter_font_face_rules<F>(stylesheet: &Stylesheet, device: &Device,
callback: &F) where F: Fn(&str, &Source) {
pub fn iter_font_face_rules<F>(stylesheet: &Stylesheet, device: &Device, callback: &F)
where F: Fn(&Atom, &Source) {
iter_font_face_rules_inner(&stylesheet.rules, device, callback)
}

View file

@ -13,7 +13,7 @@ macro_rules! define_css_keyword_enum {
};
($name: ident: $( $css: expr => $variant: ident ),+) => {
#[allow(non_camel_case_types)]
#[derive(Clone, Eq, PartialEq, FromPrimitive, Copy)]
#[derive(Clone, Eq, PartialEq, FromPrimitive, Copy, Hash)]
pub enum $name {
$( $variant ),+
}