[프론트엔드 성능 최적화] (8)

yongkini ·2023년 1월 31일
0
  • aspect-ratio 속성을 이용하면 grid를 만들 때 grid-template 속성을 주고,
.wrapper {
	width:100%;
	aspect-ratio : 16 / 9
}
.wrappedImage {
	width:100%;
	height:100%;
}

위와 같이 세팅만 해줘도 16: 9비율인 직사각형 요소들로 구성시킬 수 있다(min-width, 이런식으로 안해둬도). 이에 따라 레이아웃 이동 이슈를 해결할 수 있다.

  • useSelector 를 사용할 때
const { photos, loading } = useSelector(
	state => ({
    	photos :
        	state.category.category === 'all'
              ? state.photos.data
              : state.photos.data.filter(
              	  photo => photo.category === state.category.category
    			),
    	loading: state.photos.loading,
    }),
	shallowEqual
);

위와 같이 shallowEqual 옵션을 주면, 본래 새로운 객체를 리턴하는 형태로 써서 계속해서 리렌더링을 일으키는게 맞지만 해당 옵션을 써주면 얕은 비교를 해서 실제로 값이 변경됐을 때만 리렌더링 한다.

  • react에서 useMemo를 사용할 때의 발상과 유사하게 시간복잡도가 높은 로직을 여러번 호출해야할 상황이 있다고 하면 이전 값을 캐싱해두고, 똑같은 키(key)를 쓰면 이전에 저장해뒀던 값(value)를 리턴하도록 효율화하는 것이 좋다. 하지만, 매번 key 값이 다른 로직이라면 쓸 수 없는 방법이다. 아래는 복잡한 로직에서 cache라는 객체를 만들어서 memoization을 구현해본 것이다.
const cache = {};

export function getAverageColorOfImage(imgElement) {
  if (cache.hasOwnProperty(imgElement.src)) {
    return cache[imgElement.src];
  }

  const canvas = document.createElement('canvas');
  const context = canvas.getContext && canvas.getContext('2d');
  const averageColor = {
    r: 0,
    g: 0,
    b: 0,
  };

  if (!context) {
    return averageColor;
  }

  const width = (canvas.width =
    imgElement.naturalWidth || imgElement.offsetWidth || imgElement.width);
  const height = (canvas.height =
    imgElement.naturalHeight || imgElement.offsetHeight || imgElement.height);

  context.drawImage(imgElement, 0, 0);

  const imageData = context.getImageData(0, 0, width, height).data;
  const length = imageData.length;

  for (let i = 0; i < length; i += 4) {
    averageColor.r += imageData[i];
    averageColor.g += imageData[i + 1];
    averageColor.b += imageData[i + 2];
  }

  const count = length / 4;
  averageColor.r = ~~(averageColor.r / count); // ~~ => convert to int
  averageColor.g = ~~(averageColor.g / count);
  averageColor.b = ~~(averageColor.b / count);

  cache[imgElement.src] = averageColor;

  return averageColor;
}
profile
완벽함 보다는 최선의 결과를 위해 끊임없이 노력하는 개발자

0개의 댓글