简体   繁体   English

React:使用返回的 JSX 中的值在功能组件 VS 中声明变量

[英]React: Declaring a variable inside a functional component VS using the value inside the returned JSX

Is there any kind of performance difference between the following pieces of code?以下代码段之间是否存在任何性能差异? (Note: These are very simple examples): (注意:这些都是非常简单的例子):

const FunctionalComponent = props => {
  const a = <span>Hello World</span>;
  return (
    <h1>
      {a} {props.counter}
    </h1>
  );
};
const FunctionalComponent = props => {
  return (
    <h1>
      <span>Hello World</span> {props.counter}
    </h1>
  );
};

I can't seem to find a straight answer on figuring out if there's any kind of performance difference between declaring a variable like this in a functional component VS directly using the value inside the returned JSX (even if it's just a small performance difference).我似乎无法找到一个直接的答案来确定在功能组件中声明这样的变量与直接使用返回的 JSX 中的值之间是否存在任何性能差异(即使它只是一个很小的性能差异)。

Well, the second snippet of code should be the more efficient one to use.好吧,第二段代码应该是使用效率更高的代码段。

The straight forward answer is that there's a direct correlation between the size of a downloaded script and the performance on the client-side.直接的答案是,下载脚本的大小与客户端性能之间存在直接关联。

Obviously as you said, this is just a simple example and the effect of declaring one extra variable will be negligible.显然正如您所说,这只是一个简单的示例,声明一个额外变量的效果可以忽略不计。 However, as you add more variables there will be a slightly reduced performance since additional memory allocation and fetching happens.但是,当您添加更多变量时,性能会略有下降,因为会发生额外的 memory 分配和获取。

Fetching occurs when you use the variable after you declare it.当您在声明变量后使用它时,就会发生获取。 Somewhere on the low level processing of your script the value of your a const will have to be fetched from memory every time you use it.在脚本的低级处理中,每次a const 时,都必须从 memory 中获取它的值。 In your example, instead of just adding <span>Hello World</span> to your dom, you're fetching <span>Hello World</span> from memory (since its stored in a variable).在您的示例中,您不是仅将<span>Hello World</span>添加到您的 dom,而是从 memory 获取<span>Hello World</span> (因为它存储在变量中)。 And then it's added to the dom.然后它被添加到dom。

Memory allocation simply refers to the act of creating the const and storing its value in memory. Memory 分配只是指创建 const 并将其值存储在 memory 中的行为。

To sum it all up: Instead of the functional component just returning elements that will be added to the dom, the functional component is storing a constant, fetching the value of the constant and then returning the dom elements.总结一下:功能组件不是只返回将添加到 dom 的元素,而是存储一个常量,获取常量的值,然后返回 dom 元素。 On a larger scale there could be significant performance loss as a result of this.在更大的范围内,这可能会导致显着的性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM