Scripts: array methods visit every element of a host collection

Array.prototype methods called on a host collection with more than 4,096
elements, such as forEach over a document's page items, visited only the
indices held as properties. A host collection keeps its elements in the
host, so those methods skipped every element. They now visit every
index of an object whose class has an indexer.

Each element read also called the indexer twice, once to test presence
and once to read the value. The methods now read an index of such an
object with one call, the one `k in object` makes, and take its answer as
the element.
This commit is contained in:
dotCooCoo committed 2026-11-30 15:22:04 -08:00
1 parent 639ce5004e
commit a353ebef69
4 files changed
+68 -12

No files matched your search

+15 -2
View File
@@ -314,8 +314,21 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Value> {
interp.get_from(o, &key_of(k), &Value::Object(o))
}
fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<bool> {
interp.has_property_indexed(o, &key_of(k))
/// The element at `k` when the object or its prototypes have one: [[HasProperty]], then [[Get]].
/// An object of a host class with an indexer answers an array index with one call of the indexer,
/// made as `k in object` makes it, and has the element when the answer is not `undefined`.
fn element_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Option<Value>> {
let key = key_of(k);
if crate::value::array_index(&key).is_some()
&& let Some(f) = interp.host_indexer(o)?
{
let v = interp.host_index(&f, o, crate::Data::Number(k), true)?;
return Ok((!matches!(v, Value::Undefined)).then_some(v));
}
if !interp.has_property_indexed(o, &key)? {
return Ok(None);
}
interp.get_from(o, &key, &Value::Object(o)).map(Some)
}
/// The estimated bytes a new element adds.
+8 -9
View File
@@ -5,11 +5,12 @@
//! the range is much longer than the object has properties (a sparse array such as
//! `new Array(4294967295)`), so a long empty range costs nothing and no index is allocated for
//! it. The list of indices is made again whenever a script adds an index property to any object
//! while the method runs. Every index visited takes a unit of fuel.
//! while the method runs. An object of a host class with an indexer has every index of the range
//! visited, since its elements are not properties. Every index visited takes a unit of fuel.
use super::{
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, get_at, has_at, length_of, method, native, new_array, object_to_string, put_at,
require_callable, to_integer,
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, element_at, get_at, length_of, method, native, new_array, object_to_string,
put_at, require_callable, to_integer,
};
use crate::heap::{Class, NativeKind, ObjId};
use crate::interp::{Abrupt, Interp, JsResult, strict_eq};
@@ -121,7 +122,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> {
impl Indices {
fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec<Map>) -> JsResult<Self> {
let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None };
if hi.saturating_sub(lo) > DENSE_SPAN {
// An object of a host class with an indexer holds its elements in the host, not in
// properties, so every index of the range is visited.
if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() {
let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add);
if hi - lo > (present as u64).saturating_mul(8) {
it.sparse = Some(it.gather(interp)?);
@@ -206,11 +209,7 @@ impl Indices {
/// The element at `k` when the object or its prototypes have one.
fn element(interp: &mut Interp, o: ObjId, k: u64) -> JsResult<Option<Value>> {
let k = k as f64;
if !has_at(interp, o, k)? {
return Ok(None);
}
get_at(interp, o, k).map(Some)
element_at(interp, o, k as f64)
}
/// ToObject of `this`, kept reachable while `f` runs.
+2 -1
View File
@@ -21,7 +21,8 @@
//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the
//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what
//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as
//! a third argument, and is true when it gives a value other than `undefined`.
//! a third argument, and is true when it gives a value other than `undefined`. The `Array.prototype`
//! methods read each index of such an object with that one call and take its answer as the element.
//!
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
//! member of its class and of the classes it descends from, apart from the members that are not
+43
View File
@@ -1035,6 +1035,49 @@ fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
assert_eq!(calls.get(), 1);
}
/// A realm with `it`, a host collection of `len` numbers whose element `i` is `i`, and the count
/// of the indexer's calls.
fn numbers(len: usize) -> (Realm, Rc<Cell<u32>>) {
let mut r = realm(10_000_000);
let calls: Rc<Cell<u32>> = Rc::default();
let seen = calls.clone();
let index: HostFunction = Rc::new(move |a| {
seen.set(seen.get() + 1);
match a.get(1) {
Some(Data::Number(n)) if *n < len as f64 => Ok(Data::Number(*n)),
_ => Ok(Data::Undefined),
}
});
let length: HostFunction = Rc::new(move |_| Ok(Data::Number(len as f64)));
let class = HostClass {
name: "Numbers".into(),
parent: None,
members: vec![("length".into(), HostMember::Get(length))],
info: Vec::new(),
index: Some(index),
construct: None,
};
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Numbers", &[1.0]))]).unwrap();
(r, calls)
}
#[test]
fn array_methods_visit_every_element_of_a_long_host_collection() {
let (mut r, _) = numbers(5000);
let source = "var n = 0; Array.prototype.forEach.call(it, function () { n++; }); \
var m = Array.prototype.map.call(it, function (x) { return x; }); \
[n, m.length, m[4999], Array.prototype.lastIndexOf.call(it, 0), Array.prototype.indexOf.call(it, 4999)].join()";
assert_eq!(r.run(source).unwrap(), JsValue::String("5000,5000,4999,0,4999".into()));
}
#[test]
fn array_methods_call_the_indexer_once_for_each_element() {
let (mut r, calls) = numbers(3);
let source = "var s = 0; Array.prototype.forEach.call(it, function (x) { s += x; }); s";
assert_eq!(r.run(source).unwrap(), JsValue::Number(3.0));
assert_eq!(calls.get(), 3);
}
#[test]
fn a_converted_function_reads_each_argument_as_its_list_says() {
let mut r = realm(1_000_000);