当前位置:网站首页>Long list performance optimization scheme memo

Long list performance optimization scheme memo

2022-07-07 10:44:00 Weave_ network

Have a brief understanding of memo

In the field of computer , Memorization is an optimization technology scheme mainly used to improve the speed of computer programs . It stores the returned results of expensive function calls , When the same input occurs again , The cached data is returned , So as to improve the computational efficiency .

notes : stay 《JavaScript Ninja Secret 》 Of 3.2.2 In the festival 「 Self memory function 」 There is such an introduction in :

Memorization is a process of constructing functions , Be able to remember the last calculation result . In this shell , When the function calculates the result, the result is stored according to the parameters . In this way , If another call uses the same parameters , We can directly return the last stored result instead of calculating it again . Avoiding repetitive and complex calculations like this can significantly improve performance .

memo effect

Check whether the content to be rendered is the same as the previous rendering , If the two are the same , Then the last rendering result will be retained .

vue3.2 A new performance optimization instruction has been added in v-memo

Remember the subtree of a template . Elements and components can be used . The instruction receives a fixed length array as a dependency value for memory comparison . If each value in the array is the same as the last rendering , Then the update of the whole subtree will be skipped . for example :

<div v-memo="[valueA, valueB]">
  ...
</div>

When the component is re rendered , If valueA And valueB All remain the same , So for this <div> And all its child nodes will be updated skip . in fact , Even virtual DOM Of VNode Creation will also be skipped , Because the memory copy of the subtree can be reused .

It is important to declare memory arrays correctly , Otherwise, some updates that actually need to be applied may also be skipped . with Empty dependency array Of v-memo (v-memo=“[]”) stay Functionally equivalent to v-once.

combination v-for Use

v-memo Only targeted optimization for performance sensitive scenarios , There should be few scenes to use . Rendering v-for A long list of ( Longer than 1000) Probably its most useful scenario :

<div v-for="item in list" :key="item.id" v-memo="[item.id === selected]">
  <p>ID: {
   { item.id }} - selected: {
   { item.id === selected }}</p>
  <p>...more child nodes</p>
</div>

When the components selected When the state changes , Even the vast majority item Nothing has changed , a large number of VNode Will still be created . Used here v-memo Essentially represents “ Only in item Update it when it changes from unchecked to checked , vice versa ”. this Allow each unaffected item Reuse the previous VNode, And completely skip the difference comparison . Be careful , We don't need to put item.id Included in the memory dependency array , because Vue Can automatically from item Of :key Infer it from .

Be careful

stay v-for Use in v-memo when , Make sure they are Used on the same element . v-memo stay v-for Internal is invalid .

v-memo It can also be used for components , In some extreme scenarios where the update check of sub components is not optimized , Manually prevent unnecessary updates . however , Say it again , Developers are responsible Specify the correct dependent array , To avoid necessary updates being skipped .

React 16.6.0 Released in React.memo()

React.memo() What is it?

React.memo() and PureComponent Very similar , It helps us control when to re render components .

Component only in its props Re render when changes occur . Generally speaking , In the component tree React Components , As long as there is a change, it will go through the rendering process . however adopt PureComponent and React.memo(), We can just let some components render .

const ToBeBetterComponent = React.memo(function MyComponent(props) {
    
  // only renders if props have changed
})

React.memo() acceptable 2 Parameters , The first parameter is zero Components of pure functions , The second parameter is used for contrast props Control whether to refresh , And shouldComponentUpdate() The function is similar to .

import React from "react";

function Child({
     seconds}){
    
    console.log('I am rendering');
    return (
        <div>I am update every {
    seconds} seconds</div>
    )
};

function areEqual(prevProps, nextProps) {
    
    if(prevProps.seconds===nextProps.seconds){
    
        return true
    }else {
    
        return false
    }

}
export default React.memo(Child,areEqual)

Components applied to

Because only the components that need to be rendered are rendered , So this is a performance improvement .
PureComponent Depend on class Can be used . and React.memo() You can talk to functional component Use it together .

import React from 'react';

const MySnowyComponent = React.memo(function MyComponent(props) {
    
  // only renders if props have changed!
});

// can also be an es6 arrow function
const OtherSnowy = React.memo(props => {
    
  return <div>my memoized component</div>;
});

// and even shorter with implicit return
const ImplicitSnowy = React.memo(props => (
  <div>implicit memoized component</div>
));

React.memo() It's a function of higher order , It is associated with React.PureComponent similar , But a function component, not a class

import React  from 'react';

export default class extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            date : new Date()
        }
    }

    componentDidMount(){
        setInterval(()=>{
            this.setState({
                date:new Date()
            })
        },1000)
    }

    render(){
        return (
            <div>
                <Child seconds={1}/>
                <div>{this.state.date.toString()}</div>
            </div>
        )
    }
}

React.memo() And Redux

import React from "react";

function Child({seconds,state}){
    console.log('I am rendering');
    return (
      <div>
        <div>I am update every {seconds} seconds</div>
        <p>{state}</p>
      </div>
    )
};
const mapStateToProps = state => ({
    state: 'React.memo() Use in connect()( Inside )'
});
export default connect(mapStateToProps)(React.memo(Child))
原网站

版权声明
本文为[Weave_ network]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070830420206.html