yejineee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- tags: vue --- # FE 성능 최적화 - especially vue & vuex vue와 vuex에서 성능 최적화를 위하여 신경써야할 것은 무엇이 있는지 알아보자. 여러 블로그들을 읽으며 정리하려고 한다. ## 5 methods for optimizing Vue.js applications - [출처 : 5 methods for optimizing Vue.js applications](https://blog.logrocket.com/methods-optimizing-vue-js-applications/) ### 1. lazy loading route components lazy loading이라는 것은 객체나 애플리케이션의 어느 한 부분의 초기화를 그것이 필요해질때까지 지연시키는 것을 말한다. 원래 뷰는 하나의 js파일로 번들되지만, 레이지 로딩을 적용하면, 각 컴포넌트들이 여러 작은 파일들로 컴파일될 수 있다. 이 덕분에 브라우저는 더 빠르게 로딩할 수 있고, 새로운 파일은 유저가 새로운 루트로 이동했을 때, 요청된다. 레이지로딩의 단위는 뷰 라우터로 등록한 단위이다. router 컴포넌트 안에 등록된 모든 컴포넌트들이 번들 파일의 일부분이 된다. 관련 포스트이다. https://blog.logrocket.com/how-async-components-can-optimize-performance-in-vue-apps/ ```javascript // in router.js file import Vue from 'vue' import Router from 'vue-router' const Home = () => import('./routes/Home.vue'); const Profile = () => import('./routes/Profile.vue'); Vue.use(Router) export default new Router({ routes: [ { path: '/', component: Home }, { path: '/profile', component: Profile } ] }) ``` 이런식으로 컴포넌트를 등록하면, 웹팩에서 알아서 코드를 그룹으로 나누어준다. **연관된 라우트에 있는 컴포넌트들을 같은 그룹에 묶어줄 수 있다.** 같은 그룹으로 만들고 싶은 컴포넌트들에 같은 이름을 지정하면 된다. 그러면 웹팩이 또 알아서 같은 이름의 컴포넌트들을 하나로 묶어준다. ```javascript // specifying the same chunk for components const Profile = () => import(/* webpackChunkName: "profile" */'./routes/Profile.vue'); const ProfileSettings = () => import(/* webpackChunkName: "profile" */'./routes/ProfileSettings.vue'); ``` ### 2. 외부 라이브러리의 사용을 줄이기 이것저것 설치해서 필요없는 코드로 인해 앱의 크기가 너무 커지는 것을 주의하라. 패키지를 설치하기 전에, 더 가벼운 다른 패키지가 없는지를 확인해라. 패키지를 찾아보기전에, 원하는 기능이 natively 구현할 수 있는지를 확인하라. native feature가 크로스 브라우징 이슈가 있거나, 구현하기 어렵다면, 그때 패키지를 선택하라. 패키지를 찾아볼때는 여러 다양한 패키지중에서 따져보고 선택하라. 패키지가 modular pattern이 내장되어있고, tree-shaking을 지원하는 것이 프로젝트에 적합하다. - modular pattern : 연관된 변수나 함수들을 하나의 scope에 묶는 패턴이다. 이러한 코드는 전체 애플리케이션에 걸쳐서 재사용되므로, 같은 함수를 여러 지점에서 반복해서 정의하지 않아도 된다. https://medium.com/technofunnel/data-hiding-with-javascript-module-pattern-62b71520bddd - tree shaking 사용하지 않는 코드를 제거하는 방식이다. import구문에서 특정 부분만 가져도록 하여, 모듈의 특정 부분만 가져오게 된다. 이를 통해 사용하지 않는 자바스크립트 코드들을 제거할 수 있다. ```javascript= // 유틸의 일부만 가져온다. import { unique, implode, explode } from "array-utils"; ``` 주의할 점은 바벨로 es6 module이 cjs로 변환되는 것을 막아야 한다. 그래야 웹팩이 디펜던시 트리를 분석해서 사용하지 않는 디펜던시를 제거한다. - [트리쉐이킹으로 자바스크립트 페이로드 줄이기 - TOAST UI](https://ui.toast.com/weekly-pick/ko_20180716) ### 3. ## 대용량 데이터의 처리 방법과 성능 최적화 방법 (Vue.js Performance) - [출처 : [Vue.JS] 대용량 데이터의 처리 방법과 성능 최적화 방법 (Vue.js Performance)](https://kdydesign.github.io/2019/04/10/vuejs-performance/) - vue.js 성능 개선에서 가장 중요한 **핵심은 Observe**이다. - 부가적으로 **defineReactive를 이해**해야 한다. - **computed와 getter의 사용을 최소한**으로 해야 한다. -> 왜...? **vue의 반응형에 대해 깊이 있게 알고 있다면, Vue의 성능 최적화를 이룰 수 있다.** 필자의 프로젝트 구조 1. SPA 2. 빅데이터 처리 한 페이지에서 보여줘야 하는 row 데이터는 10만건 정도. 3. client paging 처리 10만건의 데이터를 표현해야 했다. `virtual scroll 기법`을 사용해서 현재 화면에서 실질적으로 보여주는 row만 DOM을 생성하고, 이후 스크롤을 하면 이어서 DOM을 업데이트 해주면, 생성되는 DOM의 갯수는 제한된다. 그러나, virtual scroll을 구현하기 위한 조건에 충족되지 않아서(모든 TR 태그의 높이는 동일해야 한다.) 하지 못하였다. 특성상 client 측에서 페이징 처리를 해야 했다. 클라이언트 측 페이징은 페이지를 넘길때마다 API를 통해서 데이터를 조회하는 것이 아니라, 최초 모든 데이터를 조회한 후에 프론트측에서 페이징을 해야한다는 것이다. 4. jQuery 컴포넌트 사용 jQuery 는 뷰의 반응형 대상이 되지 않는다. 따라서 데이터가 변경되면 jQuery 내부에서 DOM을 수동으로 업데이트 해주어야 한다. vue의 성능 최적화 방법은 결론부터 말하자면 **JS Heap Memory 최소화**시키는 것이라고 한다. 대용량 데이터에 대해 서버 페이징 처리 없이 FrontEnd 측에서 처리하려면, 최대한 js heap memory를 낮춰야 한다. js heap memory가 증가할수록, UI 상의 모든 컴포넌트가 느려진다. 메모리가 증가하는 이유는 무언가를 **읽고 쓰고 할 때** 증가한다. 변수를 선언하거나, **객체의 속성을 읽거나 수정**할때도 증가한다. -> 객체 속성을 읽을 때는 왜 증가하지? 메모리 누수에 대한 몇 가지 조치 방법이 있다. -> 이것에 대해서는 좀 더 알아보도록 하자. - 전역 변수 사용 - 타이머와 콜백 - 외부에서의 참조 - closure의 사용 Vue에서 가장 중요한 것은 **객체의 속성을 읽거나 수정**하는 항목이다. **Vue는 data, state, computed, getters와 같은 모델이 선언되면 `defineReactive`를 통해 해당 객체가 반응형 관리 대상으로 등록**이 된다. 이 과정에서 **각 개체마다 `Observe`가 생성되고, 내부적으로 getter/setter가 생성**된다. `__ob__`가 있고, getter와 setter가 붙은 것을 확인할 수 있다. <img width='70%' src='https://i.imgur.com/cthH0g3.png' /> 만약, 10만건에 대해서 객체가 반응형이면, 객체 1개마다 getter/setter가 생성될 것이다. 이 데이터가 단순 배열이 아닌 객체라면 더 많은 getter/setter가 붙게 된다. 10만건에 대해 이러한 과정을 거치는 것이 js heap memory를 증가시키는 이유가 된다. 그래서 **대용량의 데이터를 갖고 있는 모델은 Vue의 반응형 관리대상에서 제외**시키고자 한다. ### 모델에 대한 가공은 최소화하기 API를 통해 온 데이터를 프론트에서 가공해서 사용해야 하는 경우들이 있다. 이럴 때 가공은 컴포넌트에서 computed나 watch, 또는 스토어의 getters를 이용하게 된다. 그러나 대용량 데이터를 가져야하는 모델에 대해서는 최대한 데이터를 가공하지 않아야 한다. 즉, computed와 getters를 최대한 사용하지 않아야 한다는 뜻이다. -> 이분은 대용량 데이터를 다루니, 이런말을 하시는 것 같다. 모든 경우에 적용되는 말은 아니겠지? 모델이 반응적이면 그만큼 js heap memory를 차지하기 때문이다. ### 모델에 대한 반응형 제거 대용량 데이터를 가진 모델에 대해서는 Vue의 감지 대상에서 제거한다. 즉, Observe가 생성되지 않게 처리해야 하는데, 이를 vue의 관점에서 처리해야 한다. - **Object.freeze() 사용** `Object.freeze()`를 사용한다. `Object.freeze()`는 해당 객체를 read only로 처리하기 떄문에, 이 객체에 대해서 속성을 추가/제거/수정할 수 없고, 해당 객체에 대한 프로토타입 또한 변경할 수 없다. **read only 객체가 되었기에 vue의 감지 대상에서도 제외**된다. Object.freeze()를 사용하는 시점은 state에 저장할 시점 (mutation)이다. ```javascript //state export const state = { bookList: [] } // mutations export const mutations = { setBookList (state, payload) { state.bookList = Object.freeze(payload) } } // actions export const actions = { getBookList ({commit}) { // API call // ... commit('setBookList') } } ``` - Object.freeze() 수정 만약 Object.freeze() 처리된 객체를 수정할 수 없지만, 만약 수정을 해야한다면, 객체를 복사한 후 수정해야 한다. 복사된 객체는 vue의 감지 대상이기 때문에, 다시 vue의 감지 대상에서 제거하려면 수정 후 Object.freeze()를 처리해야 한다. ```javascript // mutations export const mutations = { addBookList (state, boolList) { // lodash clone let cloneBookList = _.cloneDeep(bookList) cloneBookList.splice(1, 0, {name: 'add book', date: '2019-04-08'}) state.bookList = Object.freeze(cloneBookList) } } ``` - Object.freeze - Array.prototype.map 배열 또는 컬렉션의 경우 map을 사용하여 새로운 배열 요소를 반환할 수 있다. 이 리턴 자체를 Object.freeze()로 처리한다. ```javascript //state export const state = { bookList: [] } // mutations export const mutations = { addBookList (state, boolList) { // lodash map let cloneBookList = bookList.map(book => book.name = 'kdydesign') state.bookList = Object.freeze(cloneBookList) } } ```

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully