Skip to content

Truly independent web browser

LibJS: Find the fly strings of short keys by their characters

Andreas Kling51261a3e62f6
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 2a943af64e5..5a2741be9c4 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -457,6 +457,7 @@ pub(crate) fn default_host_enqueue_finalization_registry_cleanup_job(
}
pub const STRING_TO_ATOM_CACHE_SIZE: usize = 256;
+pub const CHARACTERS_TO_ATOM_CACHE_SIZE: usize = 256;
pub const FLY_STRING_CACHE_SIZE: usize = 1024;
pub const NUMERIC_STRING_CACHE_SIZE: usize = 1000;
pub const LARGE_NUMERIC_STRING_CACHE_SIZE: usize = 1024;
@@ -469,6 +470,17 @@ pub struct StringToAtomCacheEntry {
pub atom: Option<Utf16FlyString>,
}
+/// Remembers the fly string of a short ASCII string that became a property key before it had storage, for the next
+/// string with the same characters (see PrimitiveString::property_key()).
+#[derive(Default)]
+pub struct CharactersToAtomCacheEntry {
+ /// The hash of the characters that were looked up here without being found, if no lookup since then found
+ /// `fly_string`. Characters only replace `fly_string` with theirs the second time in a row, so that keys that are
+ /// only used once leave it alone.
+ pub missed_hash: u64,
+ pub fly_string: Option<Utf16FlyString>,
+}
+
#[derive(Trace)]
pub struct NumericStringCacheEntry {
pub number: Cell<u64>,
@@ -554,6 +566,9 @@ pub struct Vm {
pub names: CommonPropertyNames,
/// What functions without parameter names share, since an empty Rc slice is an allocation of its own.
pub(crate) no_parameter_names: Rc<[Utf16FlyString]>,
+ /// The fly strings of short ASCII strings that became property keys before they had storage, found by a hash of
+ /// their characters. Every collection empties this cache, so that it keeps no fly string alive for long.
+ characters_to_atom_cache: RefCell<Box<[CharactersToAtomCacheEntry; CHARACTERS_TO_ATOM_CACHE_SIZE]>>,
/// The strings in these two caches are weak: the sweep callback drops the ones that die.
string_to_atom_cache: RefCell<Box<[StringToAtomCacheEntry; STRING_TO_ATOM_CACHE_SIZE]>>,
fly_string_cache: Box<[Cell<Option<Gc<PrimitiveString>>>; FLY_STRING_CACHE_SIZE]>,
@@ -723,6 +738,9 @@ impl Vm {
names: CommonPropertyNames::new(),
no_parameter_names: Rc::from([]),
string_to_atom_cache: RefCell::new(Box::new(core::array::from_fn(|_| StringToAtomCacheEntry::default()))),
+ characters_to_atom_cache: RefCell::new(Box::new(core::array::from_fn(|_| {
+ CharactersToAtomCacheEntry::default()
+ }))),
fly_string_cache: Box::new([const { Cell::new(None) }; FLY_STRING_CACHE_SIZE]),
numeric_string_cache: Box::new([const { Cell::new(None) }; NUMERIC_STRING_CACHE_SIZE]),
large_numeric_string_cache: Box::new(
@@ -1556,7 +1574,8 @@ impl Vm {
});
}
- /// Drops the weak cache entries of strings that died in this collection.
+ /// Drops the weak cache entries of strings that died in this collection, and every entry of the caches that each
+ /// collection empties.
fn remove_dead_strings_from_weak_caches(&self, sweep: &Sweep<'_>) {
let is_dead = |string: Gc<PrimitiveString>| sweep.is_dead(string);
for cache_slot in self.fly_string_cache.iter() {
@@ -1570,6 +1589,9 @@ impl Vm {
}
}
self.interned_strings.borrow_mut().retain(|_, string| !is_dead(*string));
+ self.characters_to_atom_cache
+ .borrow_mut()
+ .fill_with(CharactersToAtomCacheEntry::default);
}
/// Forgets the cells that died in this collection from the inline caches of executables and static call sites.
@@ -1947,6 +1969,12 @@ impl Vm {
&self.string_to_atom_cache
}
+ pub fn characters_to_atom_cache(
+ &self,
+ ) -> &RefCell<Box<[CharactersToAtomCacheEntry; CHARACTERS_TO_ATOM_CACHE_SIZE]>> {
+ &self.characters_to_atom_cache
+ }
+
pub fn fly_string_cache(&self) -> &[Cell<Option<Gc<PrimitiveString>>>; FLY_STRING_CACHE_SIZE] {
&self.fly_string_cache
}
diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
index 55212ea3c1d..2b24fa0a6ce 100644
--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
@@ -5,14 +5,15 @@
*/
use core::cell::{Cell, UnsafeCell};
+use core::hash::BuildHasher;
-use ak::{Utf16FlyString, Utf16String};
+use ak::{Utf16FlyString, Utf16String, Utf16StringUnits};
use libjs_runtime_macros::Trace;
use crate::gc::class::{Class, ExternalMemorySize, GcCell, define_cell};
use crate::gc::root::MarkedVec;
use crate::gc::visitor::{Trace, Visitor};
-use crate::interpreter::vm::{StringToAtomCacheEntry, Vm};
+use crate::interpreter::vm::{CHARACTERS_TO_ATOM_CACHE_SIZE, StringToAtomCacheEntry, Vm};
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::member::NullableMember;
use crate::layout::primitive_string::{DEFERRED_KIND_MASK, INTERNED_FLAG};
@@ -128,6 +129,10 @@ fn is_ascii(code_unit: u16) -> bool {
code_unit < 0x80
}
+/// The most ASCII characters of a string that the VM remembers the fly string of by its characters, see
+/// Vm::characters_to_atom_cache().
+pub const KEY_STRING_MAX_LENGTH: usize = INLINE_STRING_CAPACITY;
+
impl PrimitiveString {
fn fly_string_cache_hash(string: &Utf16FlyString) -> usize {
u64_hash(string.raw_identity() as u64) as usize
@@ -451,7 +456,7 @@ impl PrimitiveString {
// OPTIMIZATION: A string that is not resolved yet resolves into the fly string of its key, so that every later
// key of it is its own storage. The keyed access caches of the JIT tell keys apart by that storage.
if self.deferred_kind() != DeferredKind::None {
- return PropertyKey::from(self.resolve_into_fly_string());
+ return PropertyKey::from(self.resolve_into_fly_string(vm));
}
let string = self
.resolved_utf16_string()
@@ -592,13 +597,29 @@ impl PrimitiveString {
/// Resolves a deferred string into the fly string of its contents rather than into storage of its own, and
/// returns that fly string.
#[inline(never)]
- fn resolve_into_fly_string(&self) -> Utf16FlyString {
- let fly_string = match self.deferred_kind() {
- DeferredKind::None => unreachable!("only deferred strings are resolved"),
- DeferredKind::Rope => to_utf16_fly_string(&self.as_rope_string().concatenation()),
- DeferredKind::Substring => to_utf16_fly_string(&self.utf16_string_view().to_utf16_string()),
- // NB: The few characters of an inline string are looked up before they are copied into storage.
- DeferredKind::Inline => self.utf16_string_view().to_utf16_fly_string(),
+ fn resolve_into_fly_string(&self, vm: &Vm) -> Utf16FlyString {
+ // NB: Only the pieces of a rope have to be put together to look at its characters.
+ let mut rope_characters = [0; KEY_STRING_MAX_LENGTH];
+ let length = self.length_in_utf16_code_units();
+ let few_ascii_characters = if length > KEY_STRING_MAX_LENGTH {
+ None
+ } else if self.deferred_kind() == DeferredKind::Rope {
+ self.append_ascii_characters(&mut rope_characters, &mut 0)
+ .then(|| &rope_characters[..length])
+ } else {
+ match self.utf16_string_view() {
+ Utf16View::Ascii(characters) => Some(characters),
+ Utf16View::Latin1(_) | Utf16View::Utf16(_) => None,
+ }
+ };
+ let fly_string = match few_ascii_characters {
+ Some(characters) => Self::fly_string_of_few_ascii_characters(vm, characters),
+ None => match self.deferred_kind() {
+ DeferredKind::None => unreachable!("only deferred strings are resolved"),
+ DeferredKind::Rope => to_utf16_fly_string(&self.as_rope_string().concatenation()),
+ DeferredKind::Substring => to_utf16_fly_string(&self.utf16_string_view().to_utf16_string()),
+ DeferredKind::Inline => self.utf16_string_view().to_utf16_fly_string(),
+ },
};
let string = Utf16String::from(&fly_string);
match self.deferred_kind() {
@@ -610,6 +631,52 @@ impl PrimitiveString {
fly_string
}
+ /// Copies the characters of this string of at most KEY_STRING_MAX_LENGTH code units into `characters` from
+ /// `offset` on, and moves `offset` past them. Returns false, with some of them copied, if the string or a piece of
+ /// it is not kept as ASCII.
+ fn append_ascii_characters(&self, characters: &mut [u8; KEY_STRING_MAX_LENGTH], offset: &mut usize) -> bool {
+ if self.deferred_kind() == DeferredKind::Rope {
+ // NB: The halves of a rope are not empty, so a rope this short is not deep either.
+ let rope_string = self.as_rope_string();
+ return rope_string.lhs().append_ascii_characters(characters, offset)
+ && rope_string.rhs().append_ascii_characters(characters, offset);
+ }
+ let Utf16View::Ascii(own_characters) = self.utf16_string_view() else {
+ return false;
+ };
+ copy_few_bytes(&mut characters[*offset..], own_characters);
+ *offset += own_characters.len();
+ true
+ }
+
+ /// The fly string of the at most KEY_STRING_MAX_LENGTH ASCII `characters`.
+ ///
+ /// OPTIMIZATION: Programs put the same few keys together again and again, like "on" + type, and each time the key
+ /// is a new string. The VM remembers the fly strings of such keys by their characters, so finding
+ /// one again takes no storage for the characters and no lookup in AK's fly string table.
+ fn fly_string_of_few_ascii_characters(vm: &Vm, characters: &[u8]) -> Utf16FlyString {
+ let hash = foldhash::fast::FixedState::default().hash_one(characters);
+ let index = hash as usize & (CHARACTERS_TO_ATOM_CACHE_SIZE - 1);
+ let missed_before = {
+ let mut cache = vm.characters_to_atom_cache().borrow_mut();
+ let entry = &mut cache[index];
+ if let Some(fly_string) = &entry.fly_string
+ && matches!(fly_string.as_units(), Utf16StringUnits::Ascii(remembered) if remembered == characters)
+ {
+ entry.missed_hash = 0;
+ return fly_string.clone();
+ }
+ core::mem::replace(&mut entry.missed_hash, hash) == hash
+ };
+ // NB: The few characters are looked up in AK's fly string table before they are copied into storage.
+ let fly_string = Utf16View::Ascii(characters).to_utf16_fly_string();
+ // NB: Keys that are only used once leave the entry to the key that is used again and again.
+ if missed_before {
+ vm.characters_to_atom_cache().borrow_mut()[index].fly_string = Some(fly_string.clone());
+ }
+ fly_string
+ }
+
/// The characters of a string that is inline or resolved and ASCII.
#[inline(always)]
fn flat_ascii_characters(&self) -> Option<&[u8]> {
diff --git a/Tests/LibJS/Runtime/string-keys-made-at-run-time.js b/Tests/LibJS/Runtime/string-keys-made-at-run-time.js
index dc86774b13f..4c91dd1499c 100644
--- a/Tests/LibJS/Runtime/string-keys-made-at-run-time.js
+++ b/Tests/LibJS/Runtime/string-keys-made-at-run-time.js
@@ -51,6 +51,43 @@ describe("string keys made at run time", () => {
});
}
+ test("keys that are put together again for every access", () => {
+ const names = ["click", "change", "keydown", "focus", "blur", "input", "submit", "dblclick"];
+ const handlers = {};
+ for (const name of names) write(handlers, "on" + name, name.length);
+ let sum = 0;
+ for (let i = 0; i < 4000; ++i) sum += read(handlers, "on" + names[i & 7]);
+ expect(sum).toBe(500 * (5 + 6 + 7 + 5 + 4 + 5 + 6 + 8));
+ expect(Object.keys(handlers)).toEqual(names.map(name => "on" + name));
+
+ // Ropes of ropes, of substrings and of strings with a NUL character find the same properties.
+ const object = {};
+ for (let i = 0; i < 400; ++i) {
+ const digit = String(i % 10);
+ write(object, "a_" + digit + ("_nested_" + digit) + "_rope", i);
+ write(object, "from_" + ("a_substring_source_" + digit).slice(2, 11) + "_" + digit, i);
+ write(object, "nul\0" + "_key_" + digit, i);
+ write(object, "nul" + "_key_" + digit, -i);
+ // 32 characters fit in a string cell, and 33 do not.
+ write(object, "a_key_of_32_characters_in_all_" + digit + digit, i);
+ write(object, "a_key_of_33_characters_in_total_" + digit, i);
+ }
+ expect(Object.keys(object).length).toBe(60);
+ for (let digit = 0; digit < 10; ++digit) {
+ expect(read(object, ["a_", digit, "_nested_", digit, "_rope"].join(""))).toBe(390 + digit);
+ expect(read(object, `from_substring_${digit}`)).toBe(390 + digit);
+ expect(read(object, `nul\0_key_${digit}`)).toBe(390 + digit);
+ expect(read(object, `nul_key_${digit}`)).toBe(-390 - digit);
+ expect(read(object, `a_key_of_32_characters_in_all_${digit}${digit}`)).toBe(390 + digit);
+ expect(read(object, `a_key_of_33_characters_in_total_${digit}`)).toBe(390 + digit);
+ }
+
+ // A key keeps its property across a collection, which empties the VM's cache of such keys.
+ gc();
+ expect(read(handlers, "on" + names[7])).toBe(8);
+ expect(read(object, "a_" + "9" + ("_nested_" + "9") + "_rope")).toBe(399);
+ });
+
test("index keys", () => {
const array = [];
for (let i = 0; i < 100; ++i) {