Is anonymous function in Vue Template a performance killer?

蓝咒 提交于 2021-01-29 13:53:49

问题


I have following setup:

In Child component:

 <template>
   <div @click="clickHandler">
   </div>
 </template>
 <script>
    ...
    clickHandler() { 
     this.$emit('emittedFunction', someInfo, otherInfo)
    }
 </script>

In Parent component:

<template> 
  <child-component 
    v-for="index in 10"
    @emittedFunction="(someInfo, otherInfo) => someFunction(index, someInfo, otherInfo)"/>     
 </template>
 <script>
    ...
    someFunction(index, someInfo, otherInfo) { 
     do stuff 
    }
 </script>

This code works perfectly fine. To my question though: A friend of mine saw this code snippet and remarked in comments, that "anonymous functions in Vue Templates are a performance killer" and I should do it another way...he obviously didn't explain how. I can't find anything on this topic in vue documentation or stack overflow. I also don't understand why would this kind of code 'kill' performance? Is he right? If yes, why? If not, why not? Is there a way to refactor my code, if it's actually bad?

Thanks for help.


回答1:


Your friend is referring to the fact that templates are compiled to render functions, which are run on each re-render.

The problem they are referring to is that assigning an anonymous function has a small overhead due to handler being different in each render, meaning Vue can't re-use the hander and causes it to re-render the node with the listener.

This could introduce a performance issue indeed, but it is unlikely you will run into or write a code that's slow because of this. More often than not if your component is re-rendering that frequently that the overhead compounds to be noticeable, that means you should fix the re-rendering trigger rather than this.

So I wouldn't go as far as to say its "a performance killer", but more like an "optimization opportunity".

To be on the safe side, you could refactor it using closures, something like this:

<template> 
<child-component 
  v-for="index in 10"
  @emittedFunction="someFunction(index)(someInfo, otherInfo)"
/>     
</template>

<script>
   ...
   someFunction(index) { 
    return (someInfo, otherInfo) => {
      // this is a closure, you have access to the index.
    };
   }
</script>

While this looks weird, it doesn't create a new function on each render, it only creates a new function when the event is emitted and it is not tied to rendering.



来源:https://stackoverflow.com/questions/58922485/is-anonymous-function-in-vue-template-a-performance-killer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!