[Vuejs]-Is anonymous function in Vue Template a performance killer?

3đź‘Ť

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.

👤logaretm

Leave a comment