The concept of polymorphism saturating inline caches

When considering inline caches, it seems that there is no check for "or further down in the hidden class tree" (which would be costly without some trick). Even though an instance property from a base class would always be at the same offset, accessing a base class property with many different subclass instances could potentially overwhelm its inline cache (or maybe not? It's possible that I am mistaken - strongly typed languages usually handle this scenario, so perhaps there is a trick involved). This concept also applies to objects in general.

This led me to ponder: instead of subclasses, would it sometimes be more effective to have two separate objects - one with the base properties and another with the subclass properties, both referencing each other?

Class extension version:

class A {
  x = 0;
}
class B1 extends A {
  y = 0;
}
class B2 extends A {
  z = 0;
}
const b1 = new B1();
const b2 = new B2();

const f = (p: A) => { p.x; };
// Different hidden classes.
f(b1);
f(b2);

Linked objects version:

class A<T> {
  x = 0;
  extension: T;
  constructor(extension: T) { this.extension = extension; }
}
class B1 {
  a: A<B1>;
  y = 0;
  constructor() { this.a = new A(this); }
}
class B2 {
  a: A<B2>;
  z = 0;
  constructor() { this.a = new A(this); }
}
const b1 = new B1();
const b2 = new B2();
const a1 = b1.a;
const a2 = b2.a;

const f = <T>(p: A<T>) => { p.x; };
// Same hidden class.
f(a1);
f(a2);

Does this approach have any noticeable performance impact? The typical response might be "don't worry about it until you've confirmed it's a bottleneck", but it's still a question worth exploring.

Answer №1

Simply put, the answer is yes.

When subclassing, it can result in excessive polymorphism if an engine uses hidden classes and equality comparisons on these hidden classes (as seen in V8). This doesn't necessarily mean that hidden classes are problematic--they have both advantages and limitations, like any engineering technique.

To avoid this issue, modifying the object layout can be a helpful approach. The method you choose will depend greatly on your specific requirements. Bidirectional links may not always be necessary; for example, a variant that could suffice for common usage scenarios is:

class A {
  x = 0;
  extension;
  constructor(extension) { this.extension = extension; }
}

function MakeB1() {
  return new A({y: 0});
}
function MakeB2() {
  return new A({z: 0});
}
// Subsequent steps will be similar to the initial example, but using "MakeB1" instead of "new B1":
const b1 = MakeB1();
...
f(b1);

You may consider adding a type property in class A, allowing for operations such as

if (a.type == B1) ProcessB1(a) else if (a.type == B2) ProcessB2(a);
.

Does this impact performance noticeably?

Sometimes, it could...

I suppose the general rule is to not worry unless you've confirmed it's affecting performance significantly

Exactly. Most applications won't require concern, but for certain performance-critical sections, optimizations like these could make a substantial difference. Profiling is essential for identifying areas in your application that may benefit from optimization.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with making a call to retrieve an image from a different directory in ReactJS

This is how it appears <img className='imgclass' src={"../" + require(aLc.value)} alt='' key={aLc.value} /> I am trying to create a path like ../m/b/image.jpg, where aLc.value contains the path /m/b/image.jpg. I need to add only ...

Does the structure of this Angular 2 project align with the requirements of Angular CLI?

I found a helpful tutorial on user registration and login using Angular 2 at the following link: However, when I attempted to use 'ng serve' instead of 'npm start' as advised in the tutorial, I received an error message stating: &apos ...

Choose all the checkboxes alongside the markers on Google Maps

On this page , I have included a checkbox labeled "Select All" at the bottom, which automatically checks all other checkboxes. Although the code below achieves what I want, the marker icons are not showing up. How can this be fixed? $(document).ready(func ...

What is the reason the child component is not being displayed?

The code within the APP.js component looks like this: import React from "react"; import Exam from "./exam.js"; export default function App() { return ( <Exam> <h1>hashemi</h1> </Exam> ); } Similarly, the ...

Hide jQuery dropdown when mouse moves away

I am working on designing a navigation bar with dropdown functionality. Is there a way to hide the dropdown menu when the mouse pointer leaves both the navbar menu and the dropdown itself? I have tried using hover, mouseenter, and mouseleave but due to my ...

An interface designed for enums containing nested types

My task involves creating an interface for the state using an enum as a key and object as a value. How can I designate the enum as the key type? export enum Language { CS, EN } const [userInput, setUserInput] = useState<IUserInput>({ [Lan ...

Adjusting webpack configuration to incorporate an additional entry file

Hey there! I've run into a bit of an issue with React. I've created a NavBar component, saved it in JSX form in 'home.js', and it's rendering perfectly in my index.html. Now, I'm trying to create a "Login" component, but after ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

I'm curious – what exactly does `useState(null)[1]` do within React hooks?

Recently, I've started utilizing React hooks in my code. There was this interesting syntax useState(null)[1] that caught my attention, although now I can't seem to recall where I first saw it. I'm curious about the difference between useSta ...

Choose a pair of outcomes when utilizing Group By in a sqlite query

Let's dive into a complex scenario with an illustration: Consider a sqlite table with various fields (id, language, title, etc.) Each title can have multiple languages associated with it. id -- language -- title -- publication -- ...

Encountered 'TypeError: Illegal invocation' while attempting to update from version 1.2

Update: It appears that the issue could be linked to Chrome version 43. I reverted back to version 42 and everything seems to be functioning properly. Update: I have filed an issue on the Angular Github repository. The error seems to be originating from ...

Attempting to pass an asynchronous initial state to the useReducer method is resulting in an undefined return value

I am facing an issue where I am fetching asynchronous data in the parent component and trying to use it as initialState in VersionContainer. However, when I pass this initialState to the context provider, the values in ContentVersionProvider end up being ...

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

Adjustable size for web page elements

I am currently designing a web page using a basic template structure. The layout includes a header, top navigation bar, side navigation panel, main content area, and footer. While working on this project, I created a similar design in a jsfiddle demo. Ho ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

Employ SVG clusters as a sophisticated alternative to bars in D3 graphs

Imagine you have a complex data visualization created using D3. You want to go beyond just basic shapes like rectangles and instead build units with different graphics elements, such as rectangles, triangles, text labels, and background rectangles grouped ...

Trying out deletion of items from a React-managed list using Cypress testing

A React list was developed to allow users to delete items by clicking a button. The deletion process is implemented as follows: const handleRemove = (index: number) => { onChange(fieldName, (prevState) => { return { ...prevState, ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

Angular 2 - utilizing dependency injection to access services from within other services

I have developed two Angular 2 services. One of them is a custom Http class with unique functionality: ServerComms.ts import {Injectable} from 'angular2/core'; import {Http} from 'angular2/http'; @Injectable() export class ServerComm ...