메인 스레드에서 연산 작업하기
레이아웃 작업을 하다보면 자바스크립트를 통해 계산되고, 렌더링 시켜야하는 순간들이 종종 있다. 업무 중 보고서 리포트에 GIF 형태의 움직이는 이미지 파일을 각각의 스크린샷으로 분리해야하는 상황이 생겼는데, 작은 이미지의 경우에는 상관없지만 큰 이미지의 경우에는 브라우저에 부하를 발생시킨다는 위험성이 있었다.
gifuct-js 라이브러리를 연동하였고, 연동 코드를 살펴보면 비동기 함수 안에 메인스레드에서 연산을 하는 코드가 많이 보이는 것을 확인할 수 있다.
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { decompressFrames, parseGIF } from 'gifuct-js'
const image = ref<string | null>(null)
const fileImage = ref<File | null>(null)
const decompressImage = ref<ReturnType<typeof decompressFrames>>([])
const isDecompressing = ref(false)
const screenshotUrls = ref<string[]>([])
const handleImageChange = (event: Event) => {
const input = event.target as HTMLInputElement
const file = input.files?.[0] ?? null
fileImage.value = file
if (!file) return
image.value = URL.createObjectURL(file)
}
const frameToDataUrl = (frame: ReturnType<typeof decompressFrames>[number]) => {
const canvas = document.createElement('canvas')
canvas.width = frame.dims.width
canvas.height = frame.dims.height
const context = canvas.getContext('2d')
if (!context) return ''
const imageData = new ImageData(frame.patch, frame.dims.width, frame.dims.height)
context.putImageData(imageData, 0, 0)
return canvas.toDataURL('image/png')
}
const handleDecompressFrames = async () => {
if (!fileImage.value) return
const buffer = await fileImage.value.arrayBuffer()
const gif = parseGIF(buffer)
decompressImage.value = decompressFrames(gif, true)
screenshotUrls.value = decompressImage.value.map(frameToDataUrl)
isDecompressing.value = false
}
</script>
<template>
<input type="file" accept="image/*" @change="handleImageChange" />
<div class="image-result">
<img v-if="image" :src="image" />
</div>
<button type="button" :disabled="!fileImage || isDecompressing" @click="handleDecompressFrames">
{{ isDecompressing ? 'GIF 분석 중…' : 'GIF 프레임 분해' }}
</button>
<div class="decompressed-image-result">
<img v-for="(item, index) in screenshotUrls" :key="index" :src="item" />
</div>
</template>
<style scoped lang="scss">
.image-result {
margin-top: 30px;
img {
width: auto;
height: 500px;
}
}
.decompressed-image-result {
display: flex;
align-items: center;
column-gap: 10px;
overflow-x: auto;
max-width: 1100px;
img {
width: auto;
height: 400px;
}
}
</style>
async · await 자체는 메인 스레드를 따로 만들지 않지만, await을 만나면 현재 함수만 잠시 멈추고 브라우저는 렌더링 · 클릭 처리 같은 다른 일을 계속 할 수 있다. 다만 await 뒤에 실행되는 자바스크립트 계산은 기본적으로 메인 스레드에서 실행된다.
const gif = parseGIF(buffer);
const frames = decompressFrames(gif, true);
parseGIF: GIF 파일 데이터를 읽어, 헤더 · 프레임 · 압축 정보로 구조화하는 함수decompressFrames: 구조화된 GIF의 각 프레임을 실제 RGBA 픽셀 데이터로 압축 해제하는 함수
이 GIF 파싱, LZW 압축 해제는 CPU 작업이기 때문에 GIF가 크거나 프레임이 많은 경우에 실행 중 UI가 멈추는 현상이 발생할 수 있다. ( → 메인 스레드에 부하가 발생) 그래서 이를 해결하기 위해 메인스레드의 부담을 덜고자 웹 워커 스레드를 사용할 수 있다. parseGIF()와 decompressFrames()를 웹 워커 안에서 실행하면 무거운 GIF 파싱 동안 메인 화면이 멈추지않는다. 메인 스레드는 파일 선택 · 버튼 · 클릭 · 렌더링 만을 담당하고, 웹 워커에서는 프레임 데이터를 돌려준다.
메인 스레드의 연산 작업을 웹 워커 스레드와 분배하기
parseGIF()와 decompressFrames()를 웹 워커 안에서 실행하면 무거운 GIF 파싱 동안 메인화면이 멈추지 않는다. 메인 스레드는 파일 선택 · 버튼 · 클릭 · 렌더링만을 담당하고 워커가 이미지를 만들어 돌려줘야한다. 우리가 앞선 전환 작업에 앞서 그리고 있는 청사진은 아래와 같다.
일반 방식
메인 스레드: GIF 분해 → 화면 갱신
└─ 한 줄로 처리
Worker 방식
메인 스레드: 화면·타이머·클릭 처리
Worker: GIF 분해
└─ 동시에 처리 가능
웹 워커는 사용자 브라우저 안의 별도 자바스크립트 스레드에서 처리하게 되는데, 메인 스레드와의 연산 분리를 위해 먼저 gif.worker.ts 라는 파일을 만들어 워커 파일을 구축한다.
// gif.worker.ts
import { parseGIF, decompressFrames } from 'gifuct-js'
const frameToBlob = async (frame: GifFrame) => {
const canvas = new OffscreenCanvas(frame.dims.width, frame.dims.height)
const context = canvas.getContext('2d')
if (!context) throw new Error('Canvas context를 생성할 수 없습니다.')
context.putImageData(new ImageData(frame.patch, frame.dims.width, frame.dims.height), 0, 0)
return canvas.convertToBlob({ type: 'image/png' })
}
self.onmessage = async (event: MessageEvent<ArrayBuffer>) => {
const gif = parseGIF(event.data)
const frames = decompressFrames(gif, true).map((frame) => ({
patch: frame.patch,
dims: frame.dims,
delay: frame.delay,
}))
const images = await Promise.all(
frames.map(async (frame) => ({
blob: await frameToBlob(frame),
delay: frame.delay,
})),
)
self.postMessage(images)
}
OffscreenCanvas: DOM<canvas>태그와 분리해서, 웹 워커 안에서 캔버스 그리기 작업을 할 수 있도록 만들어진 브라우저 API 이다.
위와 같이 웹 워커 파일을 구성했다면 템플릿 쪽에서는 아래와 같이 구성할 수 있다. 기존에는 메인 스레드에 자바스크립트 로직들이 즐비했다면, 모든 관련 계산 로직들이 웹 워커 쪽으로 이동한 것을 확인할 수 있다.
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'
import { decompressFrames } from 'gifuct-js'
import GifWorker from '../worker/gif.worker.ts?worker'
const gifWorker = new GifWorker()
const image = ref<string | null>(null)
const fileImage = ref<File | null>(null)
const decompressImage = ref<ReturnType<typeof decompressFrames>>([])
const isDecompressing = ref(false)
const screenshotUrls = ref<string[]>([])
const handleImageChange = (event: Event) => {
const input = event.target as HTMLInputElement
const file = input.files?.[0] ?? null
fileImage.value = file
if (!file) return
image.value = URL.createObjectURL(file)
}
gifWorker.onmessage = (event: MessageEvent<ReturnType<typeof decompressFrames>>) => {
decompressImage.value = event.data
screenshotUrls.value = event.data.map((image) => URL.createObjectURL(image.blob))
isDecompressing.value = false
}
const handleDecompressFrames = async () => {
if (!fileImage.value) return
isDecompressing.value = true
const buffer = await fileImage.value.arrayBuffer()
gifWorker.postMessage(buffer, [buffer])
}
onBeforeUnmount(() => {
gifWorker.terminate()
})
</script>
<template>
<input type="file" accept="image/*" @change="handleImageChange" />
<div class="image-result">
<img v-if="image" :src="image" />
</div>
<button type="button" :disabled="!fileImage || isDecompressing" @click="handleDecompressFrames">
{{ isDecompressing ? 'GIF 분석 중…' : 'GIF 프레임 분해' }}
</button>
<div class="decompressed-image-result">
<img v-for="(item, index) in screenshotUrls" :key="index" :src="item" />
</div>
</template>
<style scoped lang="scss">
.image-result {
margin-top: 30px;
img {
width: auto;
height: 500px;
}
}
.decompressed-image-result {
display: flex;
align-items: center;
column-gap: 10px;
overflow-x: auto;
max-width: 1100px;
img {
width: auto;
height: 400px;
}
}
</style>
클라이언트 단에서 변환해서 출력해줘야하는 것이 목적이기 때문에, 큰 GIF 파일이 오는 경우 레이아웃에 부하를 주어서는 안된다. 그렇기 때문에 타이머와 동시에 테스트를 진행해보았다. 메인 스레드에서 자바스크립트 변환 로직을 사용하는 경우, 병목 현상이 발생하여 타이머가 발생하지만 웹 워커를 사용하게 되면 타이머( → 메인 스레드에 위치)와 별개로 관련 변환 로직이 웹 워커에서 처리되기 때문에 병목 현상이 발생하지 않는 것을 확인할 수 있다.
gitWorker.postMessage를 보면 buffer, [buffer] 형태로 값을 보내고 있는데, 왜 이렇게 보낼까?
첫 번째 인자는 전달할 메세지, 두 번째 인자는 그 메세지 안에서 복사 대신 소유권을 옮길 버퍼 목록을 의미한다. 메인 스레드 → 웹 워커 스레드에서는 메세지 자체가 ArrayBuffer이다.
gifWorker.postMessage(buffer, [buffer])
// └────── └──────
// 메시지 transfer 목록웹 워커 → 메인 스레드에서는 메세지가 프레임 배열이다.
self.postMessage(frames, transfers)
// └────── └────────
// 메시지 frames 내부 buffer들의 transfer 목록두 번째 인자인 frames의 구조는 대략 아래와 같이 구성이 된다.
frames = [
{
patch: Uint8ClampedArray,
dims: { ... },
},
]transfers을 넣고, 안 넣고의 차이는 명확하게 차이난다. 기본적으로 데이터를 전송하게 되면 웹 워커 스레드로 보내거나, 메인 스레드로 보낼 때의 데이터를 복사하는 과정을 진행한다. 이 경우, 데이터의 질이 좋고 크기가 큰 경우에는 오래 걸릴 수 있다.
Worker 메모리: [patch 픽셀 데이터]
↓ 복사
메인 메모리: [patch 픽셀 데이터의 새 복사본]여기서 transfers 값을 명시적으로 넣게 되면, 실제 데이터들을 새로 복사하지 않고 그 메모리를 메인 스레드로 넘기면서 훨씬 빠르다. 이를 보통 zero-copy transfer 이라고 한다. 대신 여기서 중요한 차이가 있다.
- 메인 스레드와 웹 워커 스레드가 같은 버퍼를 공유하는 것이 아니다.
- 전송 뒤 웹 워커 쪽
patch.buffer는 분리되어 더 이상 사용할 수 없다. patch.buffer를 다시 써야한다면 전송 전에 복사하거나 다시 계산해야한다.
const transfers = frames.map((frame) => frame.patch.buffer)
self.postMessage(frames, transfers)
// 여기부터 Worker의 frame.patch는 사용하면 안 됨추가로 주의해야할 사항은 메세지(→ 위 코드에서는 frames)와 transfers 와의 상관 관계이다. transfers 데이터는 보낼 메세지 내부의 복사 대신 소유권을 옮길 버퍼 목록이다. 그래서 반드시 transfers 값은 메세지 안 내부 메모리 값 중 하나여야한다.
self.postMessage(frames, transfers)
// └────── └────────
// 메시지 frames 내부 buffer들의 transfer 목록// 메인 → Worker
gifWorker.postMessage(
{ buffer },
[buffer],
)
// Worker → 메인
self.postMessage(
{ frames },
frames.map((frame) => frame.patch.buffer),
)어떻게 개선되었을까?
요 근래 컴퓨터 사양들이 높아져서 왠만해서는 레이아웃의 딜레이가 생기는 경우는 많이 없다. 하지만 자바스크립트에서 어떠한 파일을 위한 로직이 실행될 때 파일의 크기가 상당히 큰 경우 레이아웃에 병목현상을 제공할 수 있기 때문에 GIF 사진 파일을 올리면 타이머에 어떤 영향을 줄 수 있는가로 실험을 해보았다.
기존 메인 스레드에서 모든 작업을 진행했을 때의 경우, GIF 파일을 스크린샷으로 변환 버튼을 누를 때 타이머가 멈추는 현상을 확인할 수 있었다. 반면 웹 워커 스레드를 활용한 케이스에서는 변환 버튼을 눌렀을 때 타이머와 별개로 동작하며 부드러운 레아아웃 경험을 제공할 수 있었다. 자세한 내용은 아래 영상을 통해 확인할 수 있다.
CPU 속도를 절감하고 테스트를 해보자
브라우저의 DevTools 성능 측정 탭에서 CPU 감속이 웹 워커에는 동일하게 적용되지 않는 것 같은 느낌이다. 워커 스레드도 CPU를 사용하기에 GIF 계산 자체도 느려져야하는게 정상이긴한데, 그 차이가 너무 미약하다.. 워커의 실제 장점은 CPU 감속을 무시한다기보다는 느린 계산이 메인 스레드의 다양한 상호작용(입력, 렌더링 등)을 직접 막지 않게 분리한다는 점이다. 따라서 x4 감속 결과는 메인 스레드의 롱 태스크 제거 효과를 보는데는 유효하지만 확실하지는 않은 것 같다.
일반 (속도 절감 없음)
- 메인 스레드
- 웹 워커 스레드
x4 CPU 감속
- 메인 스레드
- 웹 워커 스레드
크롬의 Dev Tools CPU 감속은 전체 CPU를 실제로 느리게 만드는 기능이 아니라, 탭의 메인 스레드를 주기적으로 멈춰서 작업이 더 오래 걸리도록 만드는 방식이라고 한다. 그래서 일반 처리 코드는 4배 가까이 느려지고, 별도의 워커 스레드에서 수행한
parseGIF→decompressFrames→frameToBlob순서 방식으로 감속되지 않는 것이었다.

댓글을 불러오는 중…