문득 prototype으로 메소드를 만들면 인스턴스들이 메소드를 공유하기 때문에 메모리를 아낄수 있다고 생각을 했다. 그런데 class는 그럼 인스턴스를 만들때 마다 함수를 생성하니 메모리를 많이 먹을까?
결론 부터 말하자면 클래스 또한 함수들을 공유한다. 하지만 화살표 함수를 만들었을 때는 그렇지 않다.
class Example {
method() {
}
}
const e1 = new Example();
const e2 = new Example();
위와 같은 경우 method를 프로토타입을 통해 참조 하고 있다. 그러나
class Example {
constructor() {
this.method = () => {};
}
}
const e1 = new Example();
const e2 = new Example();
// OR
class Example {
method = () => { };
}
const e1 = new Example();
const e2 = new Example();
이런 경우에는 각각의 인스턴스가 각각의 함수를 가지고 있게 된다. 하지만 최적화된 javascript 엔진 에서는 이를 최적화 할 수 있다고 하지만 잘 모르겠다.
react에서 함수형 컴포넌트를 사용해야 할 이유가 생긴 것 같다.
추가적으로 static 메소드의 동작
class Foo {
bar() {console.log('bar');}
static baz() {console.log('baz');}
}
const f = new Foo();
f.bar(); // bar
Foo.baz(); // baz
Foo.bar(); // error
f.baz(); // error
참고
https://stackoverflow.com/questions/51464318/arrow-function-vs-class-methods-memory-footprint
https://stackoverflow.com/questions/7694501/class-vs-static-method-in-javascript