무심코 지나칠수있는 성능을 저해하는 사소한 실수

하태현·2021년 3월 23일
1

오늘 내가 무심코 지나쳐버린 성능을 저해하는 실수...ㅠㅠ

class Game extends PureComponent {
  state = {
    step: 0,
    bgStep: 0,
    fps: 0,
  };

  num = 0;
  elapse_time = Date.now();
  updateHandler = ({ touches, screen, time }) => {
    const FPS = Math.floor((1 / (Date.now() - this.elapse_time)) * 1000);

    this.elapse_time = Date.now(); // 현재 시간으로 초기화
    this.num += 1;

    this.setState({ fps: FPS });
    if (this.state.step > 7) this.setState({ step: 0 });
    if (this.state.bgStep > 1) this.setState({ bgStep: 0 });
    if (this.num % 10 === 0) this.setState({ step: this.state.step + 1 });
    this.setState({ step: this.state.bgStep + 0.001 });
  };
}

updateHandler() 함수는 16ms 마다 실행이 된다.
그런데 setState 마저 여러번 발생한다.
성능적으로 최악이다...

  updateHandler = ({touches, screen, time}: GameLoopUpdateEventOptionType) => {
    const result = {...this.state};
    const FPS = Math.floor((1 / (Date.now() - this.elapse_time)) * 1000);

    this.elapse_time = Date.now(); // 현재 시간으로 초기화
    this.num += 1;
    result.fps = FPS;

    if (this.state.step > 7) result.step = 0;
    if (this.state.bgStep > 1) result.bgStep = 0;
    if (this.num % 10 === 0) result.step += 1;
    result.bgStep += 0.001;

    this.setState(result);
  };

이런 부분은 잊지 말자.

profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

0개의 댓글