Arrow Functions in Class Properties Might Not Be As Great As We Think
Mockability
If you want to mock or spy on a class method, the easiest and proper way to do so is with the prototype as all changes to the Object
prototype object are seen by all objects through prototype chaining.
Let’s say we want to do some tests with our previous class A
.
A.prototype.handleLongClick
A.prototype.handleClick
is not a function.
Oops, since we used an arrow function in a class property our function handleClick
is only defined on the initialization by the constructor and not in the prototype. So, even if we mock our function in the instantiated object, the changes won’t be seen by other objects through prototype chaining.
Inheritance
Let’s define our base class A
.
If class B
inherit from class A
,handleClick
won’t be in the prototype and we can’t call super.handleClick
from our arrow function handleClick
.
If class C
inherit of class A
, but implement handleClick
as a function instead of an arrow function, handleClick
will only executes super.handleClick()
It’s because the instantiation of handleClick
in the constructor of our parent class overrides it.
C.prototype.handleClick()
will call our implementation but will fail with the previous error: Uncaught TypeError: (intermediate value).handleClick is not a function
.
If class D
is a plain class that inherit from class A
, he will have an empty prototype and new D().handleClick()
will log A.handleClick
.
Performance
Now the interesting part, let’s talk about performance.
We know that usual functions are defined in the prototype and will be shared across all instances. If we have a list of N components, these components will share the same method. So, if our components get clicked we still call our method N times, but it will call the same prototype. As we’re calling the same method multiple times across the prototype, the JavaScript engine can optimize it.
On the other hand, for the arrow functions in class properties, if we’re creating N components, these N components will also create N functions. Remember what we’ve seen in the transpiled version, class properties are initialized in the constructor. Which means if we click on N components, N different functions will be called.
Let’s see how they are doing in a benchmark with V8 engine (Chrome).
The first one is simple, we only measure the instantiation time, and we call our method one time.
Beware that number doesn’t really matter in this one, since one instantiation won’t be noticed in your application and we’re talking about operations per second and the number are high enough. I’m more concerned by the gap between our functions.
For the second one, I used a representative use case. The instantiation of 100 components — like a list — which after we called the method one time on each.
All benchmarks were run on a MacBook Pro 13" 2016 2GHz on Mac OS X 10.13.1 and Chrome 62.0.3202.
In short, to improve performance, you should declare your shared method in the prototype and only bound it to the context if you need to (if you pass it as prop or callback). It makes sense to bound our shared methods to the prototype and initialized our properties in the constructor of each instance, but methods not much.
We’re still talking about high ops/s, but we clearly see that arrow functions in class properties are not as performant as we thought.
And yes you’re right, the usage of property initializers won’t be noticed in our applications unless we instantiate many components. Yes we can see this as a premature optimization and you’re right premature optimizations are the root of all evil — with E Corp — but instead, can we see arrow functions in class properties as premature feature or misused feature? Hopefully, engines will optimizes the arrow functions in class properties.
P.S: Class properties for properties are such a great improvement!
I’ve seen this in many application and libraries, even ones that contain components we can instantiate multiple times. Should we really use this ESnext feature for class methods in our packages knowing that can impact — for the moment — our performance?
Personally, I don’t think that arrow functions in class properties are convenient enough — in some cases — at the expense of the performance.
相關推薦
Arrow Functions in Class Properties Might Not Be As Great As We Think
MockabilityIf you want to mock or spy on a class method, the easiest and proper way to do so is with the prototype as all changes to the Object prototype o
[Nagios] Error: Template 'timman' specified in contact definition could not be not found (c
ati 內容 pat ace data rcu notify track ems Check nagios配置文件報錯例如以下:[[email protected]/* */ etc]$ /usr/local/nagios/bin/nagios -v /us
Spring Boot使用thymeleaf模板時報異常:template might not exist or might not be accessible by any of the configured Template Resolvers
logs pla 開頭 spring 方法 temp ring mode acc 錯誤如下: template might not exist or might not be accessible by any of the configured Template R
異常:Error resolving template "xxx", template might not exist or might not be accessible...解決辦法
控制臺 返回值 resp body 網上 資料 必須 exist https 簡單表述:控制臺出現了這個異常:Error resolving template "xxx", template might not exist or might not be accessibl
Error_template might not exist or might not be accessible by any of the configured Template Resolver
錯誤提示為: Error resolving template "login.html", template might not exist or might not be accessible b
SpringBoot增加jsp頁面支援,Error resolving template template might not exist or might not be accessible
1.增加mvc支援,一定要注意這種臺階式的配置檔案格式,,,(裡面還有空格的坑),一定要嚴格對照 2.啟動類增加一個重寫的方法 @SpringBootApplication @MapperScan("com.java.dao") public class StartApplicat
Catchable fatal error: Object of class stdClass could not be converted to string
網站資訊 文章數:581 篇 評論數:2004 條 標籤數:1184 個 頁面數:7 個 友鏈數:20 條 使用者數:13092 位 共執行:2561 天 建站日期:2011.11.17 最近更新:2018.11.17 註冊登入 據說本站已備案,不管你信不信,反正我信了. ^_^
spring boot 踩坑日記: Error resolving template "index", template might not exist or might not be accessi
訪問index時報錯: org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be a
Error resolving template [index], template might not exist or might not be accessible by any of the configured Template Resolvers
1,首先我按照網上找的在controller上面的註解改成@RestController,這個是不行的。給我返回了一個 ------------------------- /login 2,把返回的 return "/login" 改成
springboot+kotlin 啟動報錯:Configuration problem: @Configuration class 'Application' may not be final
如題,發現啟動時報錯,application.kt如下 @SpringBootApplication class Application fun main(args: Array<String>){ SpringApplication.ru
Error resolving template "index", template might not exist or might not be accessible b
出現這種問題的排查思路: 1 檢查是否路徑出現錯誤 //正確寫法 @RequestMapping({"/",&
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP
統一 apple col convert rstp stp line methods gree <?php class Car { var $color = "add"; function Car($color="green") {
java.io.FileNotFoundException: class path resource ..cannot be opened because it does not exist
java ... mod ons exc pen 方法 except open java.io.FileNotFoundException: class path resource ..cannot be opened because it does not exist
eclipse 運行 mapreduce程序報錯 No job jar file set. User classes may not be found. See JobConf(Class) or JobConf#setJar(String).
ads 不變 load style 程序 ble .class loader val 報錯信息 17/07/06 17:00:27 WARN mapred.JobClient: Use GenericOptionsParser for parsing the argumen
mac上 go-delve 安裝出現The specified item could not be found in the keychain 解決方法
mon pen 方法 rar spec hub 錯誤 sys lib 安裝go語言的編譯環境,在安裝到 delve時候出現如下錯誤: If reporting this issue please do so at (not Homebrew/brew or Hom
【Kotlin】spring boot項目中,在Idea下啟動,報錯@Configuration class 'BugsnagClient' may not be final.
post open conf png spa temp 技術 dea and 報錯如下: Exception encountered during context initialization - cancelling refresh attempt: org.spr
The type name 'IComponentConnector' could not be found in the namespace 'System.Windows.Markup'
xaml namespace 管理器 運行 alt component inf 資源管理器 class 場景:Visual Studio寫WPF項目時,想要生成XML文件,默認的WPF項目沒有引入System.XML這個dll。在【解決方案資源管理器——引用】右鍵添加了Sy
UserWarning: The installed version of numexpr 2.4.3 is not supported in pandas and will be not be used
color true mini nbsp 4.6 minimum img sed ack 問題:/usr/local/lib/python3.5/dist-packages/pandas/core/computation/__init__.py:18: UserWarni
【Android】AS警告解決方法:String literal in setText can not be translated. Use Android resources instead.
轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80166941 【錯誤】 String literal in setText can not be translated. Use Android reso
SpringBoot Field aFeign in xxxx required a bean of type 'xxx' that could not be found.
Field aFeign in xxxx required a bean of type ‘xxx’ that could not be found. SpringBoot 同一個專案,多模組之間呼叫 報錯 APPLICATION FAILED TO START