<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Weihang Lo on Medium]]></title>
        <description><![CDATA[Stories by Weihang Lo on Medium]]></description>
        <link>https://medium.com/@weihanglo?source=rss-cc5f971df1f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RFFguKTquPvpsxL_yOGcRw.png</url>
            <title>Stories by Weihang Lo on Medium</title>
            <link>https://medium.com/@weihanglo?source=rss-cc5f971df1f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 06:08:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@weihanglo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rust vs. Go]]></title>
            <link>https://medium.com/@weihanglo/rust-%E5%B0%8D%E6%B1%BA-go-ee6d1e7095f2?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6d1e7095f2</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Fri, 20 Jul 2018 08:54:24 GMT</pubDate>
            <atom:updated>2019-03-25T15:52:07.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yNpYM2KEIDSvluqGO3hjGQ@2x.jpeg" /><figcaption>From <a href="https://codeburst.io/should-i-rust-or-should-i-go-59a298e00ea9">Andrew Lader</a></figcaption></figure><blockquote><em>本文譯自 </em><a href="http://julio.meroh.net/"><em>Julio Merino</em></a><em> 的 </em><a href="http://julio.meroh.net/2018/07/rust-vs-go.html"><em>Rust vs. Go</em></a><em>。Julio Merino 目前是 G 社僱員，在 G 社工作超過 8 年，無論工作內外，都接觸開發不少 Go 語言，並撰寫 </em><a href="http://julio.meroh.net/series.html#Rust%20review"><em>Rust 點評</em></a><em>系列文，來聽聽他對 Rust 與 Go 的想法吧。</em></blockquote><blockquote><em>Thanks </em><a href="http://julio.meroh.net/"><em>Julio Merino</em></a><em> for this awesome article!</em></blockquote><p>歡迎來到「<a href="http://julio.meroh.net/series.html#Rust%20review">Rust 點評</a>」系列特別篇，也是我在系列文開始就承諾撰寫的主題，將探討一個難以忽視的大哉問：Rust 與 Go 孰優孰劣？</p><p>這麼比較並沒有根據，所以不會有標準答案。我認為人們會把這兩種語言作伙比較只因為它們幾乎同時釋出，而且 Rust 的釋出像是在回應 Go。除此之外，兩種語言都被認為聚焦在系統軟體上（system software），但其實它們大相徑庭，就算都專注系統軟體，各自目標的軟體類型也不盡相同。</p><p>Go 可以視為「做對了的 C」或是「Python 的替代品」。Go 在開發網路伺服器與自動化工具的領域發光發熱。Rust 專注在正確與安全性，定位在 C++ 與 Haskell 之間，如同之前提及，可以視為「務實的 Haskell」。儘管 Rust 的語言抽象程度很高，它仍承諾這些抽象是零成本（zero-cost abstraction），也就是說，它應該擅長寫任何系統專案。</p><p>這篇個人點評基於我用兩種語言寫了相同的專案 <a href="https://github.com/bazelbuild/sandboxfs/">sandboxfs</a>。最初實作是用 Go，而我開發了另一個用 Rust 的實驗性改寫（還沒有完全檢驗），兩個實作都通過相同的測試套件（test suite）。除了透過這次改寫來學習語言，也因為當我分析 Go 實作版本的效能時，發現熱點總是在 Go 的執行環境（runtime），我想要嘗試看看簡單的 Rust 改寫後效能能否長進，而情況似乎就是如此。隨著這次改寫，我很訝異原本的 Go 實作版本有不少潛在的並行（concurrency）漏洞，因為許多 Rust 並不允許我利用相同的設計改寫。</p><p>在開始之前，也許你會想讀讀<a href="http://julio.meroh.net/2016/03/golang-review.html">兩年前我對 Go 語言的點評</a>。讀完了嗎？我們開始吧！</p><h3>記憶體管理</h3><p>要說 Rust 與 Go 之間最明顯的差異，首推各自的記憶體管理方式。</p><p>Go 根據物件的生命週期，決定物件要配置在 stack 或 heap 上，而後者會以垃圾回收機制（garbage collection）管理。Rust 則是手動（explicit）配置在 stack 和 heap 上，而後者會透過 scopes（C++ 用語中稱為 RAII）與 ownership/move semantic 管理。</p><p>在這個領域中，典型的權衡是垃圾回收與手動記憶體管理（explicit memory management）。這代表 Go 因為垃圾回收機制帶來額外開銷，而 Rust 並不會。但對大多數軟體而言不會是個問題。試想你上一次寫效能需求高，不能有延遲，且 CPU-bound 的程式是什麼時候了。</p><p>若要高效使用 Rust，需要瞭解電腦記憶體如何運作。Go 可以赦免你不懂記憶體管理，但如同我下一節將提到的，不懂記憶體並非好事：瞭解記憶體運作是通往程式設計大師之路的重要一步。</p><p><strong>獲勝者</strong>：無法決定。Go 與 Rust 兩者都提供更不容易記憶體洩漏（memory leak）且具有優良人因設計（ergonomic）的記憶體管理機制。</p><h3>難度</h3><p>Go 是一個簡單中不失自身優雅的語言。Go 極度容易幾刻鐘內上手並搞出一堆程式碼。然而，如同我們在「<a href="http://julio.meroh.net/2018/06/rust-review-learning-curve.html">Rust 點評：學習曲線</a>」一文所述，這可能是謬誤：在你剛學了任何語言後馬上寫的程式碼都不會最符合該語言特性，最佳實踐的程式需要花更多時間熬出。</p><p>對 Rust 來說，不能否認它是一個複雜的語言，也許沒有 C++ 這麼複雜，但仍有大量的概念在其中。撰寫 Rust 程式的確需要更多精力。對應的收益是，當你的程式寫完且成功編譯，很高的機率它會安然無恙的運作。這情境無法完全套用在 Go 上，我見過太多太多執行期（runtime）錯誤崩潰了。</p><p>你要選擇自己的戰爭：快速地撰寫 Go，再花費額外的時間寫瑣細的測試與修正執行期的問題；或是花時間一步步撰寫穩健的 Rust 程式，避免構建後的問題。</p><p><strong>獲勝者</strong>：難以決定。我們可以很簡單地說 Go 贏了，但我並不想要這樣定論，因為我個人喜歡花更多時間打造一個禁得起時間考驗的程式，而非在未來還必須追蹤複雜的記憶體與線程問題。</p><h3>泛型</h3><p>Go 不支援泛型。Go 的作者們並沒有堅決反對泛型，但他們聲稱無法簡潔地實作或支援，而開始動手做之前，必須先找到完美解法。因此，人們濫用 interface {}，將之作為泛型使用，其他 Go 程式碼也無法受惠於以此實作的原生函式（如 append）。</p><p>Rust 剛好具有如你所願的泛型。這個泛型支援普通型別及 traits，而且你還可以透過 impl 與 dyn 這兩個新特性（從 2018 開始），控制 Rust 從 traits 上面產生的泛型機器碼（machine code）。</p><p><strong>獲勝者</strong>：不用多說了，非 Rust 莫屬。</p><h3>程式碼完備性（Code sanity）</h3><p>我最不能接受 Go 語言缺失的功能是沒有提供零抽象成本的方法，透過程式碼自身來編撰穩健的程式。沒錯，自動程式碼格式化和強力建議程式如何寫這兩件事很美好，但這不足以強制改善程式邏輯。我發現自己常常撰寫過長的註解來解釋一些完全不可能的條件，或為什麼特定參數可以運作，還有變數與互斥鎖之間有什麼關係⋯⋯，這些都是未來程式會崩毀的病徵：<a href="http://julio.meroh.net/2013/06/readability-avoid-comments.html">註解無法透過編譯器檢驗完備性，而且註解一定會過時</a>。只要有機會，所有東西都該以程式碼表達。</p><p>那麼，什麼我在 Rust 發現什麼 Go 缺少的功能，可令程式碼更穩健更能防範未然？</p><ul><li><strong>斷言（Assertions）</strong>。斷言之所以無價，是因為它讓碼農們得以溝通不一定明顯的意圖。Rust 有斷言，反觀 Go 沒有。呃⋯⋯Go 的確有 panic 可以來模擬斷言，但這作法不被認可，你應該永不使用它。<br>為什麼 Go 沒有斷言呢？以下是我瞎猜的：因為程式設計師常常誤用斷言來驗證使用者的輸入，這樣導致有不對或惡意輸入時產生執行期錯誤。於是，崇尚務實主義的 Go 要求把所有問題當成可以被控制的錯誤，從而避免「誤用斷言」這種情況。（嗯⋯⋯，這我過些時間想再寫一篇獨立的文章來討論⋯⋯)<br>順便提個我常常聽到的說法：你可以從寫了多少斷言來判斷一個程式設計師的經驗是否老到，而越多代表越老練。歡迎對這個想法有任何評論</li><li><strong>標註（Annotations）</strong>。有時候該用到的輸入參數沒使用到，或該檢查的回傳值沒檢查。或其他時候，你知道一個特定函式永遠不會返回，而且希望給予呼叫端這項資訊，讓編譯器閉嘴。舉個例子，缺少 return 陳述句。Go 沒有這些標註，讓程式設計是很難清楚表達意圖。而 Rust 嘟嘟好有這些標註。<br>更糟的是，Go 有些特定內部函式的行為如 panic，這些編譯器知道無法回傳，但不可能在你手寫的 Go 程式碼中表達這件事。如果考慮這問題和前面提及泛型是同個缺點，再次提及比較有點失允。</li><li><strong>註釋即文件（Docstrings）</strong>。是的，Go 有 docstrings，但神基本。雖然大部分可以正常運作，但寫了一堆 Java 之後，知道事先定義好結構的 docstrings 能提供不少價值。許多工具可協助檢驗文件的完備性。舉例來說，IntelliJ 可以驗證參數名稱是否對應真正的函式參數，並且交叉參照其他類別是否也合法。<br>Rust 的 docstrings 支援 Markdown 而比 Go 來得好些，但仍無明確的撰寫指引：似乎沒有一種標準方式撰寫，也不支援替每一項目個別撰寫文件，工具更無法交叉檢查 docstrings 是否和程式碼吻合。</li><li><strong>錯誤檢查（Error checking）</strong>。我是少數（？）喜愛 Go 手動錯誤傳遞的一分子。你說得沒錯，寫一堆錯誤檢查很惱人，但這樣做迫使你使用與其他語言不同的方式思考錯誤這檔事。<br>很不幸，Go 選擇的寫法有些問題：一個函式總是回傳一個結果值與一個錯誤，呼叫端可以決定先檢查錯誤，再檢查值。語言本身並無強制做這件事，而我看多太多太多錯誤是在檢查錯誤前先取值所導致。另一方面，Rust 帶著更高端的型別封裝了值或錯誤，加上沒有 null 這個特點，這代表呼叫端永遠不會在錯誤存在時時取得結果值，反之亦然。可以參考看看 <a href="https://doc.rust-lang.org/std/result/">Result 型別</a>還有我寫<a href="http://julio.meroh.net/2018/06/rust-review-match-keyword.html">有關 match 關鍵字</a>的文章。</li></ul><p>讓我下個結論，一個正向的聲明，這兩個語言都不提供自動型別。舉例來說，Rust 與 Go 強制碼農們整數轉型至不同大小，於是任何可能溢位（overflow/underflow）之處顯露無遺。提醒你一下：Go 在這方面比 Rust 稍強些，因為 Go 的型別別名（type alias）語義上被視為不同的型別，編譯時需要手動轉型，而 Rust 則是當作語法上的別名（就像 C typedef 所作所為）。</p><p><strong>獲勝者</strong>：Rust 輕鬆勝出。你可以主張這只是對 Go 缺乏功能的一些抱怨，而且應該接受 Go 就是這種風格，但我不行：這些抱怨就是討論上述失能讓 Go 無法寫出防範未然，晶瑩剔透的程式碼。</p><h3>效能分析</h3><p>Go 的簡便無所不在，連讓程式最佳化的工具也不例外。從效能分析（profiling）來看，Go 內建追蹤 CPU 和記憶體用量的機制，且能與 <a href="https://github.com/google/pprof">pprof</a> 工具整合。可以很容易檢查 Go 程式並取得有用的資料來最佳化。</p><p>我還沒發現任何 Rust 的分析工具可以和 Go 的工具一樣整合 pprof。當然，有一個函式庫可以生成類似 pprof 的追蹤資料，但我無法簡易上手，安裝上也有點詭異（需要 gperftools 以顯示在系統上）。<a href="http://athemathmo.github.io/2016/09/14/tools-for-profiling-rust.html">這篇舊文</a>有相關資訊和工具可供參考。</p><p><strong>獲勝者</strong>：就我目前所知，Go 在這方面大勝。</p><h3>構建速度</h3><p>打從娘胎開始，Go 就被設計為盡可能快速構建。就我所知，這是為了減少 Google 內部大型應用程式構建時間而做的嘗試。我猜測這合理解釋為什麼 Go 選擇 duck typing 來避免組件間強耦合，進而加速增量編譯（incremental compilation）。當我第一次在 NetBSD 自我建立（bootstrap）Go 整個工具鏈時，我非常震驚，整個流程只需要幾分鐘。我以前使用 clang 需要幾小時建立環境。</p><p>Rust 是家喻戶曉的編譯緩慢，所有完備性檢驗（sanity check），例如 borrow checker 和泛型，並不是白吃的午餐。我聽說有機會可以改善，但第一，我還沒研究過；第二，這說法尚未實現。</p><p><strong>獲勝者</strong>：簡單啦，Go。</p><h3>構建系統</h3><p>依照現代程式語言的慣例，Go 和 Rust 都有自己的套件管理與套件相依追蹤工具。</p><p>在 Go 語言，有窮極簡單的 Go 內建工具允許我們取得套件與它的相依套件，且無需任何設定檔就可構建整個專案。聽起來超誘人的，但事實上略違反基本工程慣例，有點危險。舉例來說，Go 的工具總是從網站如 GitHub 取得最新快照版本的相依套件，但完全沒有任何機制指定版本，也無法確保惡意程式碼混入。我認為這應是受 Google 超大單一儲存庫（monorepo）如何運作，以及「在最新版構建」（build at head）的哲學影響，但這不太符合開源社群生態的期待。顯然 Go 社群最後接受了他們需要一個更好的解決方案，有<a href="https://github.com/golang/go/issues/24301">許多提案</a>也嘗試改善這種狀況。</p><p>在 Rust 這邊，我們有 Cargo，在專案中使用 Cargo 會需要比 Go 內建機制多一點點設定，但就只有一點點：典型的 Cargo.toml 只需列出幾行相依套件和該專案基本資料（metadata）即可。Rust 社群使用 Cargo 可以解析的<a href="https://semver.org/">語意化版號</a>管理相依。換言之，Rust 和 Cargo 設計上就支援他們身處的生態系，而非趕鴨子上架。Cargo 完全是 Rust 最美好的功能之一。</p><p>有趣的是，人們可以透過 Bazel 構建 Go 與 Rust 的程式。這種情況下，Bazel 透過一系列條件（rules_go）修正了上述提及 Go 的已知問題：這些條件允許相依套件以及工具鏈固定版號。至於 Bazel 對 Rust 的支援還很陽春，對應的條件（rules_rust）並沒有太多功能。</p><p><strong>獲勝者</strong>：只考慮原生構建系統，Rust 的 Cargo 工具鏈勝出。如果把 Bazel 拉進來討論，目前是 Go 略勝一籌。</p><h3>單元測試</h3><p>對任何程式碼來說，自動化測試是確保程式依照期望執行，並保證程式成長時仍能正確執行（例如：沒有寫測試就無法做大規模的重構）。Go 這方面的表現令我嗤之以鼻，我想我會保留內容給另一篇專文討論。Go 的 testing 套件看來完全不鳥現代的測試技術，一心走自己認定的套路。那欸安捏？捨棄斷言（assertion）不用，導致只有測試函式自己可以使測試失敗，不允許其他輔助函式或固定資料（fixture）。對不複雜的單元測試來說挺誘人的，但往往不好控制。最終，更複雜的測試讓真正的待測邏輯變得更隱晦，更難以理解。</p><p>謝天謝地，Go 有個第三方函式庫 testify 提供類 JUnit 的測試框架。這函式庫使用合理的語義進行測試。較嚴重的問題是 Go 社群文化較武斷，你可能沒有機會在專案中使用它。</p><p>另一頭，Rust 的測試函式庫較貼近你預期的其他語言的行為。換言之，你有斷言可以用。我發現比較奇怪的點是，Rust 推薦你把測試寫在與待測原始碼同一份檔案中。由於我還沒寫足夠的測試，不清楚在真實世界中這種做法到底會如何？</p><p><strong>獲勝者</strong>：我很想說是 Rust，因為 Go 的測試途徑太令我失望了，但 Go 有 testify 套件存在，我必須說兩者平分秋色。</p><h3>結論</h3><p>每一種程式語言皆有優缺點，這些小小的權衡抉擇是我藉由 Go 與 Rust 做比較來 證明這個概念。在每個部分勝出的語言都不一樣，有些時候你根本無法決定誰更有優勢。</p><blockquote><em>您身為工程師的職責就是瞭解每個專案該如何權衡，並替專案選擇最佳的工具。Rust 與 Go 只是工具，挑一個最適配</em><a href="http://julio.meroh.net/2018/03/bazel-tests-in-java-part-1.html"><em>團隊</em></a><em>，專案，還有你自己吧（按照這個順序）。</em></blockquote><p>如果你希望我能更具體，我會強力推薦在座的各位學習 Rust，與 borrow checker 及 ownership 和平共處。即使最終你並沒有使用 Rust，過程中所學都會回饋到其他語言上，連 Go 也不例外。</p><blockquote><em>以上翻譯經過原作者同意，但譯者並非科班也沒有翻譯學位，若有語句不通順或不合理之處，請留言或與我聯繫，切莫直接怪罪原作者。</em></blockquote><p><em>Originally published at </em><a href="https://gist.github.com/weihanglo/3dc1af4b0c15cb9ec600f28a7b06ad2f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6d1e7095f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Podcasts Software Engineers May Love]]></title>
            <link>https://medium.com/@weihanglo/4-podcasts-software-engineers-may-love-f373ffe44e5b?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f373ffe44e5b</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[podcast]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 22:37:07 GMT</pubDate>
            <atom:updated>2018-07-11T12:47:37.589Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NPYOa05gLAlm5uAo.jpg" /><figcaption><em>Image by Nick Youngson CC BY-SA 3.0</em></figcaption></figure><p>As a non-native English speaker, I often try several methods to improve my English skills. Listening to podcasts is one of the most interesting way to practice English, especially with fascinating topics I indulge in.</p><p>Therefore, I pick some of my favorite podcasts about software engineering to share with you. Enjoy these awesome shows and don’t forget to give them some feedback.</p><p><em>(written on 2018–07–09)</em></p><h3><a href="https://softwareengineeringdaily.com/">Software Engineering Daily</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*t9marRQAcU6JDY8w.jpg" /></figure><p>If you are not afraid of information explosion, you may love <a href="https://softwareengineeringdaily.com/">Software Engineering Daily</a> (SE Daily). SE Daily delivers interviews about software technical knowledge. On each episode, SE Daily invites software engineers to share their perspective on a technical topic along with a series of well-prepared questions. The topics in SE Daily cover a wide range of software engineering stuff, such as cloud computing, block chain, data science, and so on.</p><p>SE Daily believes learning technical knowledge from podcasts will help us understand how software works. We can even start listening to SE Daily without any solid software engineering background. Jeff, the host of SE Daily, is always generous to help audiences understanding technical details in layman’s terms.</p><ul><li><strong>Episode length</strong>: ~60 minutes.</li><li><strong>Frequency</strong>: Daily.</li><li><strong>Sponsor</strong>: As a company or via <a href="https://www.patreon.com/user?u=4173731">Patreon</a>.</li><li><strong>Ad</strong>: ~7 mins in an 1 hour episode. Mostly software related.</li><li><strong>Transcript</strong>: Available.</li></ul><p>Gateway episodes:</p><ul><li><a href="https://softwareengineeringdaily.com/2018/06/19/rust-networking-with-carl-lerche/">Rust Networking with Carl Lerche</a> (highly recommended)</li><li><a href="https://softwareengineeringdaily.com/2018/06/28/chrome-and-chromium-with-david-bokan/">Chrome and Chromium with David Bokan</a></li></ul><h3><a href="http://bikeshed.fm/">The Bike Shed</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*4c3xh0pqRRS68-_m.jpg" /></figure><p>If you hear a bike bell singing, you’re right. <a href="http://bikeshed.fm/">The Bike Shed</a> is coming! Hosts Derek Prior and Sean Griffin accompany guests to talk about their development experience from Ruby, Rails, Rust to whatever catches their eyes. The Bike Shed always tries to discuss hard topics in an more relaxing way. Makes the podcast more like a friends’ talk than an formal interview.</p><p>The personal reason I pick this show is that one of the hosts Sean Griffin is the author of <a href="http://diesel.rs/">Diesel</a>, one of the best Rust ORM framework!</p><ul><li><strong>Episode length</strong>: ~40 minutes.</li><li><strong>Frequency</strong>: Weekly.</li><li><strong>Sponsor</strong>: Inquire needed.</li></ul><p>Gateway episode: <a href="http://bikeshed.fm/160">160: Praise Hands Emoji 🙌 (Vaidehi Joshi)</a></p><h3><a href="http://frontendhappyhour.com/">Front End Happy Hour</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*JUZoXXNEJItVPGnC.jpg" /></figure><p><a href="http://frontendhappyhour.com/">Front End Happy Hour</a> is the most joyful podcast as far as I know. The ONE rule of Front End Happy Hour is <em>“Choose a keyword. If the keyword is mentioned, all panelists will have a drink”</em>. Sometimes the keyword is too common to be uttered accidentally, so all panelists try to speak in an funny way to avoid speaking out that word.</p><p>Hosted by software engineers from a variety of different companies such as Netflix and Evernote. The whole Front End Happy Hour panel discuss topics concerning not only front-end but software development within a short 50 minutes. In the end of an episode, panelists would share their own picks that might be off-topic but fascinating for audiences.</p><p>Subscribe this show if you are also a drunk front-end developer!</p><ul><li><strong>Episode length</strong>: ~50 minutes.</li><li><strong>Frequency</strong>: 2 episodes per month.</li><li><strong>Sponsor</strong>: Inquire needed.</li></ul><p>Gateway episode: <a href="http://frontendhappyhour.com/episodes/ab-testing-ale-or-bourbon/">A/B testing — Ale or Bourbon?</a></p><h3><a href="https://softskills.audio/">Soft Skill Engineering</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*AkAzxNebdJZ7_dr4.jpg" /></figure><p>Unlike other podcasts mentioned above, <a href="https://softskills.audio/">Soft Skill Engineering</a> does not talk about much technical details. This podcast focuses on soft skills a software engineer needs to learn. Dave Smith and Jamison Dance would lead us to navigate every little but crucial things outside programming, such as quitting jobs without jeopardizing working relationship, or how to work with colleague who often writes code in bad grammar.</p><p>Software development is not like programming. Sometimes team management and collaborations take up a more important role than implementing features. Checkout it out if you want to level up your soft skills.</p><p>Gateway episode: <a href="https://softskills.audio/2018/06/25/episode-113-quitting-the-first-job-and-too-many-responsibilities/">Episode 113: Quitting Your First Job and Too Many Responsibilities</a></p><ul><li><strong>Episode length</strong>: ~30 minutes.</li><li><strong>Frequency</strong>: Weekly.</li><li><strong>Sponsor</strong>: As a company or via <a href="https://www.patreon.com/SoftSkillsEng">Patreon</a>.</li></ul><h3>Bonus: IRL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*HPQ4xEiW-P2p2Wmi.jpg" /></figure><p><a href="https://irlpodcast.org/">IRL</a>, an original podcast from Mozilla, is a show not only related to software engineering, but also life online and real. Today, we are surrounded by digital signals and online activities, and the Web is tightly bound to our real life. Online trolling, net neutrality, privacy policies, and many more events affect both online and offline life. Host Veronica Belmont and guests share their stories about how the Web changes our future.</p><p>As a software engineer, I wish I can utilize technologies to make the world better. However, new technology is always a double-edged sword. IRL provides us a deep dive to rethink how our online behaviors affect the Web and the real world.</p><ul><li><strong>Episode length</strong>: ~28 minutes.</li><li><strong>Frequency</strong>: About 1 episode / 3 weeks.</li><li><strong>Sponsor</strong>: Not available.</li><li><strong>Transcript</strong>: Available.</li></ul><p>That’s all of my picks.</p><h4>Now, what is your favorite podcast about software engineering?</h4><p>Leave a comment and share with us!</p><p><em>Originally published at </em><a href="https://gist.github.com/weihanglo/459df9d842f4fa494336020d3d7ce56b"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f373ffe44e5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2018 前端工程師面試心得]]></title>
            <link>https://medium.com/@weihanglo/2018-%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E9%9D%A2%E8%A9%A6%E5%BF%83%E5%BE%97-125e633db3a2?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/125e633db3a2</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[面試]]></category>
            <category><![CDATA[前端]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 14:30:21 GMT</pubDate>
            <atom:updated>2018-07-11T12:46:58.627Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BS97ThCCI_NQ3EKoOjnyxA.jpeg" /><figcaption>三次面試中唯一一張照片</figcaption></figure><p>這是我在 2018 年 Q1 的求職面試心得，不算實習的話，就是第一次正式求職。記錄下來作爲人生里程碑，也分享給大家參考。</p><h3>背景</h3><p>森林系畢業，沒參與過任何資工必修課，是個大四才起步的自學傻子，啟蒙語言是 R。大四時協助教授建置 Linux server 並擔任 server admin。畢業前進入業界擔任 iOS 開發實習生，並在畢業後轉正職，2017 年 Q3 才開始全職開發前端工程。正職工作經驗約 1.5 年。</p><p>我的優勢是學習力旺盛、有 native app 開發經驗、熟悉且熱愛 Linux 和 command-line、熟悉電子書市場與相關技術、善於溝通傾聽而不堅持己見、喜愛分享所學所見。</p><p>我的劣勢是對 UI 較不在行、CS 知識不夠紮實、臨場反應不佳易緊張、沒有跑過真正的 TDD 和嚴謹的軟體開發流程。</p><p>希望我的背景能給同樣境遇的朋友一些參照。</p><h3>求職需求</h3><p>由於前東家是上櫃公司，規模不小，制度完善，但也稍缺彈性，所以求職希望以新創公司為主。</p><p>以下依優先順序排列，薪資等基本需求不列入：</p><ul><li>新創團隊或具有新創氛圍</li><li>技術討論風氣盛。</li><li>有能力相仿或更強的 co-worker，不必自幹。</li><li>工作流程明確。</li><li>重視軟體品質（CI／CD、單元測試）。</li><li>同事年齡相近。</li><li>對社會有正面意義。</li></ul><h3>應徵企業列表</h3><p>以下是這段時間我有去應徵的企業，如果你對細節沒興趣，可以<a href="https://medium.com/@weihanglo/2018-%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E9%9D%A2%E8%A9%A6%E5%BF%83%E5%BE%97-125e633db3a2#104b">直接 end</a>。</p><ul><li><a href="https://medium.com/@weihanglo/2018-%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E9%9D%A2%E8%A9%A6%E5%BF%83%E5%BE%97-125e633db3a2#fdd3">CakeResume：錄取但婉拒</a></li><li><a href="https://medium.com/@weihanglo/2018-%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E9%9D%A2%E8%A9%A6%E5%BF%83%E5%BE%97-125e633db3a2#03a4">Hahow 好學校：錄取</a></li><li><a href="https://medium.com/@weihanglo/2018-%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%B8%AB%E9%9D%A2%E8%A9%A6%E5%BF%83%E5%BE%97-125e633db3a2#da27">Appier 沛星互動：錄取</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*AO1qvjuNra509pVfa5A8iw.png" /></figure><h3><a href="https://www.cakeresume.com/">CakeResume</a></h3><ul><li>職缺：全端工程師</li><li>應徵方式：使用 CakeResume 投遞 CakeResume 的履歷</li></ul><p>若是近年來想求職的朋友，想必對 <a href="https://www.cakeresume.com/">CakeResume</a> 不陌生，CakeResume 是線上履歷編輯平臺，利用拖拉元件的方式，快速搭建個性履歷，並提供企業刊登職缺。</p><h4>動機</h4><p>會想應徵全端工程師是因在學期間協助實驗室架設 server 與 DB，對後端頗有興趣。看到 CakeResume 全端缺便躍躍欲試，自己對新創團隊的運作方式十分好奇，加上媒體轉載許多創辦人的創業過程分享，頓時熱血沸騰，從頭打造服務百萬用戶的機會實屬難得。</p><h4>面試</h4><p>面試地點是在 AppWorks 之初創投的空間，由於我是約週一晚間面試，因此只有創辦人來面試我，一問之下，才發現公司規模比想像中更迷你。面試內容不外乎自我介紹、作品展示等，並沒有技術考題。創辦人很善於傾聽，會順着你的話瞭解你的人格特質與能力，整體而言，面談十分舒服，相談甚歡。後來我們開始大談各種技術選型，因爲新創的緣故，目前是用開發較快的 Rails，比較缺乏大公司那種完整的 CI／CD 流程，我表達了工作的預期，雖然薪資與工作環境沒有符合我的需求，但感覺創辦人希望我能考慮考慮，或許是人格特質符合徵才需求吧！</p><h4>結果</h4><p>週末之前就收到回覆。美其名是錄取通知，其實比較類似邀請成爲夥伴，共同奮鬥打拚。當下其實滿兩難的，CakeResume 的理念很棒，創辦人很誠懇又熱情，甚至最後盡量將薪資拉近我的預期，但礙於我內心希望有 co-worker 共同討論成長，不希望完全自幹，所以就婉拒了，非常感謝創辦人的盛情邀約。</p><p>在面談中，創辦人有句話一直縈繞在我心中：「CakeResume 不是科技業求職平台，透過履歷編輯工具，協助相對資訊弱勢的其他族群曝光自己，展現他們的長才！」平臺上早有許多廚師、理髮師等各行各業的人使用履歷服務。如此崇高的理念，令我非常感動，也回憶起踏入軟體圈的初衷與期許。誠摯推薦大家使用分享 CakeResume 的服務！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*PkjMaYraXgQs3kh8ysbdZQ.png" /></figure><h3><a href="https://hahow.in/">Hahow 好學校</a></h3><ul><li>職缺：前端工程師</li><li>應徵方式：主動在 Hahow 官網投遞履歷</li></ul><p><a href="https://hahow.in/">Hahow</a> 是在華語市場頗爲知名的線上課程募資平臺，至今有幾十萬會員數與豐富多樣的線上課程。和其他平台的差異在於 Hahow 使用募資的方式，確保學生人數與課程品質，並提供同學與老師，還有同學間完善的交流與作業批改機制。</p><h4>動機</h4><p>應徵 Hahow 工程師並非偶然，早在 2017 Q3 就看到楚楚動人的徵才文，不過當時沒打算離職。爾後不久就讀到 Hahow 在他們的<a href="https://tech.hahow.in/">技術 Medium</a> 上許多軟工與對軟體品質的分享，對於許多還在 rsync tar作部署備份的手動工程師，有如荒漠甘泉。 一月初偶然在 Facebook 上瞥見徵才貼文，期限只剩幾刻鐘，「此時不投，更待何時」。這時候你絕對會慶幸<strong>平常有整理履歷和 LinkedIn</strong>。</p><p>由於 Hahow 的面試流程較有意思，接下來以時序分段落介紹：</p><h4>線上測驗</h4><p>幾天後，收到 Hahow 的回覆，獲得第二階段線上測驗的門票，三十分鐘 3 題 JavaScript 演算法，用的是 RemoteInterview.io 平台。老實說我其實滿緊張的，LeetCode 刷得不多，又沒受過專業演算法訓練，甚至上機當天還在擔心 online editor 沒有 VIM keymap，還好平台編輯器使用 CodeMirror，沒有太奇怪的 keymap 設定，但也因此失去一些寶貴作答時間。</p><p>題目就是 LeetCode Easy 的程度，也有考到 closure 概念（有點忘了），不過實在是太緊張，有個基本到不行的 Dynamic Programming 題，寫到最後居然卡住，當時就覺得駭啊，只好繼續調 CodeMirror 的 VIM 設定放鬆心情。默默祈禱 Hahow 評分除了過測資，也會參考解題邏輯。</p><h4>第一階段面試</h4><p>幾天後，收到 on-site 面試邀約。面試官約莫 30 歲，是個略靦腆但好相處的人，一開始就介紹自己是四個 co-funder 之一，以三十人的小公司來說，不難想像面試都是 co-funder 自己來。同樣從背景，工作經歷問起，也有技術相關的討論，這時我才知道，原來 React + RxJS 早已滲透每個人心中，新創公司不是已經導入就是正在導入，Hahow 也不例外。突然話鋒一轉，面試官開始技術面試，主要是考觀念，例如 SPA 爲什麼流行？如何在 SPA 做 SEO 等等，必須「清楚理解每種技術的優劣」，並學會「在不同情境下選用適合的技術」。也有 JavaScript 必考題：Promise 與 callback 的比較，還好之前有<a href="https://weihanglo.tw/posts/2017/javascript-concurrency-promise/">認真研究 Promise</a>。除此之外，少不了白板面試，題目是簡單的 array 題，只是腦袋突然打結，讓面試官撒泡尿才寫完。</p><p>接下來是求職者發問時間，我必問的問題之一是：「你如何得知今天該做什麼」，其實我並不在意團隊跑不跑 scrum 這種形式上的流程，只要有明確的任務管理，不會讓工程師閒着發呆，或是任意插件就很 OK 了，熱門的開發流程並不總是適合每個團隊。</p><p>由於是新創公司，我也詢問了公司目前資金與營運狀況，面試官也順便介紹了其他 co-funder 的背景，過程就像老友聊天一樣放鬆，一不小心面試就從九點聊到十二點，蠻不好意思的。</p><h4>小專案</h4><p>一面完，面試官告訴我有一個 mini project，主要是了解 coding style 和實際的能力，有辦法的話，可以嘗試使用一些 promising 的技術展現自己。其實做 mini project 的成本不低，不過我還是稍微花了心力，在週末趕完，<a href="https://github.com/weihanglo/hahow-recruitment">程式碼在此</a>，有興趣可以參考。個人認爲小專案不僅可體現實力，更是一個有條理地說明程式架構的機會，寫出讓人快速理解文件，反而比實作還燒腦啊！</p><p>幾天後，就收到回覆，Hahow 針對專案實作提了一些問題，我也簡單提供修正與改善的方法，就進入最後面試階段了。</p><h4>第二階段面試</h4><p>二面主要是看個人特質及目標與公司的契合度，面試官是兩個 co-funder，一個技術背景，另一個負責營運。同樣也是自我介紹，聊聊爲什麼想要和 Hahow 一起奮鬥，這部分與一面重複，不過有了前次經驗，這次嘗試抓住對方想聽的重點，也訓練自己在壓力下維持口條清晰。</p><p>由於前份工作也有教育相關的部分，我就開始針對 Hahow 的政策、理念和目標開始發問，再導引到自身擅長的領域。這邊就不諱言的舉個例子，Hahow 的理念固然是推廣教育，學那些學校不會教的事，但對於經濟弱勢的朋友，有些課程仍然負擔不起，有沒有解決辦法？其實這不只是 Hahow 的問題，坊間甚至整個國民教育，都有資源不均的情形，當我們揮舞著「唯有讀書高」的大旗，是否有些人根本無法心無旁騖地好好學習？</p><p>這次面試一不小心又談了兩個多小時，不過目前遇到的 3 個 co-funder 都很誠懇，也願意將許多營運面的狀況分享給我。傳說在 Hahow 的 slack 上，這些都是公開的祕密，也許所謂扁平化的管理就如斯。</p><h4>結果</h4><p>經過一番電話交涉，最終 Hahow 給了符合預期的 package，雖然過程有點冗長，仍然感謝 Hahow 如此器重我。</p><p>Hahow 非常注重學生老師互動，也有心推廣各式各樣的技能，而非獨尊程式設計。從 <a href="https://blog.hahow.in/">Hahow 的部落格</a> 就可一窺這群文青多麼理想多麼可愛，希望看倌也能從 Hahow 豐富的課程中學到些什麼，翻轉臺灣金錢學歷至上的教育。</p><p>哦還有一點，Hahow 的男女比例很 OK。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-tlRCbJR6_q5AzhfKSuug.png" /></figure><h3><a href="https://www.appier.com/">Appier 沛星互動</a></h3><ul><li>職缺：前端工程師</li><li>應徵方式：主動在 Appier 官網投遞履歷 + 內部推薦</li></ul><p>談到 <a href="https://www.appier.com/">Appier</a>，應該無人不曉，被譽爲下個台機電，未來的新創獨角獸，全球百大 AI 企業。目前主要產品是 AI 廣告與跨螢追蹤等。客戶多是大型跨國企業。Appier 可謂近來最火熱的公司之一。</p><h4>動機</h4><p>很早就知道有前端缺，礙於自信不足，沒有嘗試，因緣際會下，朋友說有缺可以幫忙內推，加上很喜歡 JSDC 2017 兩位 Appier 講者給的 RxJS 與 FP 的演說，就主動循正常管道投遞履歷（原以為履歷直接交給朋友就行）。</p><h4>第一階段面試</h4><p>履歷過關後，便是第一次 on-site 面試，地點是在臺北信義區的總部內。我承認我是土包子，看到門禁設備像捷運一樣要領磁扣過閘門，開始懷疑走錯地方了。</p><ol><li><strong>工程師</strong></li></ol><p>這次面試共有三組人馬，第一組是兩位前端 leader，與前面兩間公司不同，很直接就切入技術層面，先是問選擇 Redux-Observable 實作 Hahow 小專案的理由（不是 Appier 面試嗎，怎麼問起 Hahow 來了呢？），蠻欣慰地是他們很用心看 GitHub 和作品集。接下來繼續追問 Observable 的概念，不知道哪根筋不對，我居然拿出筆電 demo 簡單的 Observable 實作。面試官就說：「既然拿出筆電了，那我們來<strong>從頭實作一個 Promise</strong> 吧！我跟你同時寫。」實作 promise 談何容易，雖然面試官不斷提點我方向，可惜最後只有半成品，還好實作方向正確。</p><p>這硬仗過後，便是口頭觀念問答：</p><ol><li>原型鍊的觀念</li><li>解釋 CORS</li><li>爲什麼送 request 伺服器沒收到 cookies（因爲沒有加 withCredentials）</li><li>何謂 third-party cookies</li></ol><p>感覺起來都是 tracking 或廣告常遇到的 issue，除了 CORS 最近實作 <a href="https://github.com/weihanglo/sfz">static file server</a> 剛好有接觸，其他答得勉勉強強，不過面試官們很和善，也很願意聊技術，據說連 Reason 都進 production 了，果真玩很大！</p><p><strong>2. PM</strong></p><p>這關大概算是 PM 面試，一位漂亮的 PM 姐姐和 PCMan（沒錯，就是 PCMan），PM 姐姐講話條理分明，也很親切，主要詢問個人特質和溝通技巧，遇到難以溝通的情況會怎麼應對；輪到 PCMan 就毫不留情開了白板演算法，選擇一種語言寫實際程式碼。「API 忘記了就儘管問沒關係」PCMan 如是說。我當下居然沒選 JavaScript 而選擇許久沒碰的 Python，導致作答花了不少時間（應該要選 Rust 的）。題目雖不難，但 PCMan 會依循你的程式碼脈絡深入探討你怎麼分析複雜度，例如我提到 amortized analysis，PCMan 就順著追問平攤的算法與定義，甚至最後討論到 Python built-in function 實作上與 for-loop 解法的 memory allocation 比較，果然功力深不可測。</p><p>既然遇到 PCMan，我就順便問了一些 <a href="https://github.com/weihanglo/sfz">side project</a> 遇到的疑惑，雖然沒有直接替我解惑，卻提點不少方向，讓我順利修正一些 issue，很高興能看見傳說中的人物。</p><p><strong>3. 人資</strong></p><p>人資姐姐這部分就比較輕鬆，是常見的人資問題，也閒聊在此工作的光景，但前面兩關耗時太多，早已超過下班時間，對姐姐挺不好意思，不敢聊太多。這邊要幫忙緩頰，我覺得不管是工程師、PM 還是 HR，每個人都非常友善，沒有鄉民口中的趾高氣昂，也許當事人才知道實情，別再任意散播啦。</p><h4>第二階段面試</h4><p>二面安排在週六上午，很神奇的時間，想必面試官是高階主管。</p><p><strong>1. CTO</strong></p><p>第一關是 CTO，風格獨特的技術人，先談談過去的經驗，而後從經驗延伸相關問題，大概如下：</p><ol><li>爲什麼用 React，jQuery 不好嗎？</li><li>什麼是 closure？</li><li>什麼是 CORS？哪些請求需要開啟 CORS？</li><li>你說 JSONP 可以 cross origin，那怎麼實作 JSONP？</li><li>客戶說網頁跑很慢，你要怎麼檢測？</li></ol><p>後來 CTO 似乎翻到我寫的「<a href="https://medium.com/@weihanglo/answers-to-chernys-interview-questions-ed5b35dce930">所謂最好的面試題</a>」，</p><p><a href="https://medium.com/@weihanglo/answers-to-chernys-interview-questions-ed5b35dce930">試答 Cherny 所謂「最好的前端面試題」</a></p><p>就拿來考，我有點太緊張，一直試圖回想自己寫了什麼，搞得答題像背答案，答得不盡理想。最後我問了公司未來的產品與規劃，當然沒辦法得知新產品的內容，但依稀聽得出來 Appier 不僅在廣告下足功夫，且將邁向下個階段了。</p><p>這邊平反一下，也許 CTO 面試時會打斷面試者說話，但通常都是離題或誤解才會出手。而且用心觀察，可以發現 CTO 只是說話急促，並非盛氣凌人，當天我有告知 CTO 他的語速過快，而他也有試圖慢下來講（雖然還是很快）。我認爲每個人的言談都自成風格，若不適可以當場提出，相信大多數人會試著改善，事後發文抨擊對事情無益。</p><p><strong>2. CEO/COO</strong></p><p>CEO 和 COO 這一關偏向人格特質，先是問了離職原因，我說想找年齡相近的 co-worker，CEO 馬上笑笑地說自己很老要被淘汰了，我趕緊補上說因爲前同事都生小孩去了，COO 接著說我才剛生完小孩呢！這下慘了，馬上踩了兩個雷。之後不免俗地問了自認為的優缺點，對自己的期許，以及生涯規劃。我也提問了公司目前最大的困難是什麼？答案不是資金而是跨國溝通，蠻令人訝異的，但也由此得知 Appier 已經走過新創風險最高的那里路。</p><p>不論是 CTO、CEO 還是 COO，身爲公司的領導人物，卻沒有一絲高姿態，也願意親自面試工程師，尊重每位面試者，難能可貴，大家別在捕風捉影啦。</p><h4>結果</h4><p>錄取。縱使整個過程有個人特殊狀況，仍感謝 Appier 各位大大協助我排除，讓我可以很放心的面試。Appier 真的高手如雲，能在這邊工作學習絕對進步神速。</p><h3>一些想法</h3><p>原本想要分享一些面試準備方式，但發現自己沒有依循特定模式準備，LeetCode 也很偶爾刷一刷，而且四處都有大神分享如何拿到 FLAG 或 BAT offer 的文章，我就不誤人子弟了。</p><p>從 3 人剛孵化的團隊，到 30 人逐漸穩定的熱血新創，面試到近 300 個員工的未來獨角獸。每一個創業階段都經歷過，會看到起步期趕著做出 MVP 證明理念，初期商業模式與理想的拉鋸，到擴張期捨我其誰的傲氣，甚是有趣。雖然自己沒能力領導團隊，有幸身在其中參與面試也滿足了。</p><p>一連串的面試下來，我覺得最有價值的是「了解自己」，爲了面試，你必須定期整理自己的履歷，反省自己的長處與缺點，並檢視這段歲月究竟成長多少。有時候我們會汲汲營營薪資福利，但機運勉強不來，寶貴的面試經驗才是你最可靠的財富。失敗了，就過半年一年再投一次吧！</p><p>我最喜歡問面試官：「你喜歡在這裡工作嗎？」很多時候，得到的是意味深長的微笑，我依稀記得以前部門主管的一席話：「工作不是人生的目標，卻占了一半的人生，學習與之共處才能快樂工作。」工作當然有愉快也有不爽，不過，在臺灣這種低薪、高工時、職場霸凌嚴重、勞權低落的就業環境，除了想辦法讓慣老闆無所遁形外，也別忘了鼓勵那些願意照顧員工，讓員工快樂工作的優良企業。</p><p>最後，堅持初衷，擇你所愛，選了就不要後悔。</p><p>祝福各位都能找到理想中的工作！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125e633db3a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Is New Terminal In VS Code So Fast?]]></title>
            <link>https://codeburst.io/source-reading-how-is-new-terminal-in-vs-code-so-fast-10a40f7f8792?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a40f7f8792</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Thu, 19 Oct 2017 16:16:14 GMT</pubDate>
            <atom:updated>2018-07-11T12:47:59.943Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNIK4yTnqfplRfmJSrKpPQ.png" /><figcaption>Microsoft — Visual Studio Code</figcaption></figure><p>Last week, a new version (1.17) of Visual Studio Code was released. While there are many fascinating improvements and features introduced, the one that caught my eyes is “Integrated Terminal performance” section. Let’s check out what they’ve done!</p><p><em>(written on 2017–10–19, based on Xterm.js v3, VS Code 1.17)</em></p><h3>Old Performance Issue</h3><p>The integrated terminal in VS Code is powered by another popular open-source project <a href="https://github.com/sourcelair/xterm.js">“Xterm.js”</a>, which is currently maintained by <a href="https://www.sourcelair.com/">SourceLair</a> and community contributors. There are many real-world use cases of Xterm.js, such as <a href="https://www.rstudio.com/products/RStudio/">RStudio</a> and <a href="https://github.com/jupyterlab/jupyterlab">JupyterLab</a> (Ah ha! Data scientist!), not to mention SourceLair itself. One can say that Xterm.js dominates web-based terminal world as React does in front-end development.</p><p>As same as other web-based HTML terminal emulators, old versions of Xterm.js are powered by old fashion. Rendering from HTMLElements, selecting text via document.getSelection, receiving DOM MouseEvents. All these works were done by a sequence of DOM manipulations.</p><p>Development in modern web technologies lowers the barriers for other devs to contribute to. Every programmer can easily pick up a JavaScript cookbook to study, then boasts about new frameworks on Github trending as he is a JavaScript expert. However, web techs also brings another significant drawback: performance.</p><p>As we mention to web performance, two key concepts should be kept in mind: <strong>reflow</strong> and <strong>repaint</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziqsO2HBrSzWgGvc.png" /><figcaption><em>Image from MDN. We focus on </em><strong><em>layout</em></strong><em> and </em><strong><em>paint</em></strong><em>.</em></figcaption></figure><h3>Reflow</h3><p>When a web page is initialized, the render engine calculates dimensions and position of all elements to layout them in proper place. This is known as <strong>layout</strong>. Although layout is a normal stage of browser rendering process, any updates of position, dimensions or other properties on a specific element after initialization will lead to an additional layout on that element, and all its child nodes need to do a extra layout, too (except nodes with absolute position). These synchronously layout calculations are called <strong>reflows</strong>, which might result in performance bottlenecks.</p><blockquote><em>Here is a list of </em><a href="https://gist.github.com/paulirish/5d52fb081b3570c81e3a"><em>what forces layout / reflow</em></a><em>. Read it to avoid reflows.</em></blockquote><h3>Repaint</h3><p>A <strong>repaint</strong> occurs when changes are made to an element’s visibility, background color, or other styles not relevant to layout. Repaints are less expensive than reflows, but also have some impact on browser responsive time.</p><h3>DOM manipulations</h3><p>Poor performance is not web techs or JavaScript’s faults. It always counts on implementation details. <a href="https://hyper.is/">Hyper</a> and <a href="https://github.com/railsware/upterm">Upterm</a> are two delightful terminal emulators based on Electron. They add many convenient features to improve our boring daily terminal lives. The pain points are their performance issues due to DOM rendering. Both rendering implementations depend on heavy DOM manipulations.</p><p>Imagine you are running a yes-like command that writes output at <a href="https://www.reddit.com/r/unix/comments/6gxduc/how_is_gnu_yes_so_fast/">full 10.2GiB/s speed</a>. You will find that your web-based terminal emulator stuck and cannot response to any mouse event anymore. The high speed yes triggers a tremendous amount of synchronous <strong>reflows</strong> and <strong>repaints</strong>. Soon, the browser becomes irresponsive.</p><h3>Optimization in Dark DOM Era</h3><p>Back to the original version before refactoring to canvas renderer (which started at <a href="https://github.com/sourcelair/xterm.js/commit/c6d4c73c">c6d4c73c</a>). VS Code used naïve way to render terminal output. We can simplify the old rendering process into following steps:</p><ol><li>Setup initial row elements corresponding to each row in terminal. That is to say, if size of the terminal is 80 * 24. It would creates 24 &lt;div&gt; representing each row.</li><li>Loops lines from current terminal buffer. Each line is an array of character data. A character data stores its own width and characters information.</li><li>Loop character data in each line. Wrap each characters as innerHTML in a &lt;span&gt; element. Remember that we need to escape special character such like &lt;, &gt; and &amp;.</li><li>Append &lt;span&gt;s to each row element. Then append each row element to terminal element.</li><li>If anything changes, repeat previous steps.</li></ol><p><strong>What a nightmare!</strong></p><p>If you are an experienced web developer, you may feel uncomfortable with all those implementation. Modifying DOM between each updates is highly expensive and leads to janky behavior. Luckily, talented maintainers of Xterm.js found their own solution to improve performance. They</p><ul><li><a href="https://github.com/sourcelair/xterm.js/blob/c6d4c73c8a8c23ce102918fc0342cf33d2986711/src/Renderer.ts#L159">Use </a><a href="https://github.com/sourcelair/xterm.js/blob/c6d4c73c8a8c23ce102918fc0342cf33d2986711/src/Renderer.ts#L159">DocumentFragment to batch DOM manipulations</a> to reduce DOM reflow/layout.</li><li><a href="https://github.com/sourcelair/xterm.js/blob/c6d4c73c8a8c23ce102918fc0342cf33d2986711/src/Renderer.ts#L35">Build an object pool</a> to reuse &lt;span&gt; elements containing characters to render. This reduce a plenty of new element creation time.</li><li><a href="https://github.com/sourcelair/xterm.js/blob/c6d4c73c8a8c23ce102918fc0342cf33d2986711/src/Renderer.ts#L67-L102">Setup a skip-frame mechanism</a> to throttle refresh rate when consuming large streamed buffer.</li><li>Implement a <a href="https://github.com/sourcelair/xterm.js/pull/670">custom selection logic</a> to support multiple pages selections instead of document.getSelection.</li></ul><p>Despite that these methods made performance much better (at least better than other popular project I’ve tried), the implementation still had some space for enhancements. For instance,</p><ul><li>Modification of &lt;span&gt;s in &lt;div&gt; rows still trigger some unnecessary reflows.</li><li>The old rendering process will always remove entire line from DOM, and then append new element to DOM, even when only a single character changed.</li><li>Though the skip-frame mechanism can free CPU from endless requestAnimationFrame events, the skip-frame itself means dropping frame from 60 FPS animation.</li><li>Most characters used in terminal can represent in ASCII code, but a browser always use UTF-16 DOMString to store the information, which may be seen as a waste of memory usage.</li></ul><h3>Simple Intro of Canvas</h3><p><a href="https://code.visualstudio.com/blogs/2017/10/03/terminal-renderer">As the recent blog post said</a>, the new canvas-based rendering engine renders 5 to 45 times faster, and reduces input latency, power usage and many more. Sounds perfect! However, not all front-end developers are familiar with canvas API. Here are some basic concepts of canvas API you need to know.</p><p>The &lt;canvas&gt; is an HTML element providing API for rendering graphics via scripting (JavaScript) on the fly. Modern browsers would also enable hardware-acceleration of canvas rendering by default. You can think of canvas API as an optimized version of browser&#39;s <strong>repaint</strong> powered by GPU.</p><h3>API Provider</h3><p>To render a 2D canvas, one developer just need to follow simple steps shown below:</p><ol><li>Create a rendering context (by creating a &lt;canvas&gt; element).</li><li>Access contexts (use canvas.getContext(&#39;2d&#39;) for 2D rendering context).</li><li>Start drawing via <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">various commands</a>.</li><li>All drawing results are rendered onto canvas element as an composited image.</li></ol><p>As you can see, learning 2D canvas rendering needs only a small amount (around 70 API for 2D context) of human memory. Most of these drawing API are style-related. As a web developer, you must have seen more CSS styles than these tiny group of drawing commands. Memorizing 70 additional methods is just a piece of cake, huh?</p><h3>Resource Saver</h3><p>Another selling points is that 2D Canvas rendering provides a plenty of <strong>pixel-awared</strong> drawing commands. Instead of updating the whole canvas element, these drawing methods let you decide your region of interest to be re-render in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas">per-pixel level</a>. Almost all drawing API provide optional coordinates and size parameters for devs to tweak what they really desire. The process of updating only changed elements is called <strong>invalidation</strong>, and that preserves much precious CPU and GPU time.</p><p>As opposed to DOM elements, styles in 2D canvas are shared between each path belongs to the canvas. No need to store inline-styling information for every elements. If you want to temporarily store your style state, you can use the standard context.save() and context.restore() methods to push/pop your styles from a stack-like context state container. That&#39;s why I call canvas a <strong>memory saver</strong>!</p><h3>Performance Booster</h3><p>As well as saving resources, canvas rendering also gives us ways to jack up performance. One is using detached canvas as an off-screen canvas or using OffScreenCanvas directly. The latter can even draw canvas in worker threads!</p><p>Another way is creating a texture atlas. A <a href="https://en.wikipedia.org/wiki/Texture_atlas">texture atlas</a> a.k.a. <strong>sprite sheet</strong>, is an image packed other small pieces of sub-images into itself. When drawing a sub-image, one can picks up the sub-image by its own texture coordinates. The reason to store images in single texture is that GPU is often more performant when accessing a large texture one time than multiple tiny images many times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*I0v4ptj29GgsgBlb.gif" /><figcaption><em>Nyancat runs on VS Code without janky!</em></figcaption></figure><h3>Canvas to the Rescue</h3><p>After understand big concepts in 2D canvas. Let’s dive into <a href="https://github.com/sourcelair/xterm.js/pull/938">the pull request</a> that made canvas renderer. First, recap what they’ve done:</p><ol><li>Texture atlas (use ImageBitmap) for ASCII codes and ANSI 256 colors. Unicode characters and true-colored text would be drawn on the fly.</li><li>Only render changes. To determine state changes, use custom GridCache to store previous state for comparisons with incoming changes.</li><li>Use four different render layers to separate concerns and reduce the whole canvas re-rendering.</li><li>Remove skip-frame mechanism because new rendering performance is extremely fast.</li></ol><h3>Texture Atlas and Color Managements</h3><p>First, we look into the texture atlas.</p><p>Xterm.js constructs a global atlas generator shared between terminals with the same configuration (defined in ICharAtlasConfig and ICharAtlasCacheEntry). This can reduces some duplicated construction if an app gets a multiple terminal instances such as VS Code. The actual time that a atlas generated is terminal being opened by calling acquireCharAtlas. Internally, acquireCharAtlas would compare between configurations (font size, char width, color, etc.) to avoid overhead works.</p><p>The private class CharAtlasGenerator does the real stuff. It sets attribute alpha to false to reduce redundant transparent compositions. Though this config seen like a limit of flexibility, the texture atlas is enough to provides frequently used colors for most text-based programs in the world. Moreover, the generator draws all ASCII code with 8 ANSI color (3 bit) in normal and bold styles onto an detached canvas in advance. That would be nearly 256 * 16 = 4096 characters pre-rendered (though some char is invisible and not printable).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m0LPhyg9qzAK5mr9.png" /><figcaption><em>That’s how the </em><strong><em>CharAtlas</em></strong><em> looks behind the scene.</em></figcaption></figure><p>All colors you need on your 5-year-old ASUS laptop is here. Whoever needs more characters atlas?</p><blockquote><em>In the beginning, I found that the CharAtlas generating actually twice (canvas element and ImageBitmap). </em><a href="https://github.com/sourcelair/xterm.js/pull/938#pullrequestreview-69391070"><em>Tyriar told me the intent</em></a><em>, what they want to achieve is not only improving the construction performance, but decreasing drawing latency.</em></blockquote><h3>Separating Render Layers</h3><p>Xterm.js separates the canvas rendering into four different layers (ordered from bottom to top):</p><ul><li>TextRenderLayer: Render background and foreground of the content.</li><li>SelectionRenderLayer: Render only selected region.</li><li>LinkRenderLayer: Render hyperlink with extra color and text decorator (underline).</li><li>CursorRenderLayer: Render different style of a blinking cursor.</li></ul><p>This can gain a performance boost since the render engine only repaint changed parts instead of the whole canvas. While constructing 4 different canvases is awesome, we lost the chance to set canvas’ alpha channel to opaque. This may lead to a performance drop on 2D graphic composition. The compositor requires extra GPU time to composite 4 additional transparent contexts. GUI framework providers always recommend that use opaque layer as possible as we can (at least <a href="https://developer.apple.com/documentation/uikit/uiview/1622622-isopaque">iOS UIKit</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#Parameters">Canvas 2D Context</a> said).</p><p>In reality, it may not cause any problem if you layer is not opaque. I have not yet done any profiling or tests. Just have a thought on this kind of situation.</p><p>On the other side, it is very pleasant to trace a well-organized source code. We do not need to plunge ourselves into each lines if we only want to understand a little part of code. And Xterm.js does this job perfectly. The separation of render layers is an awesome example. The feeling deepens even more when the codebase is written in TypeScript. As a former iOS engineer, the syntax of type annotations are very familiar and helpful to rapidly grasp the big picture of a project for a newcomer. Maybe it’s time to use TypeScript in our next project. Thanks Xterm.js contributors!</p><h3>Bugs After Breaking Changes</h3><p>Canvas renderer is awesome! Canvas renderer is promising! Canvas renderer outperforms all competitors in web-based terminal world!</p><p>Is the new renderer really that invulnerable? Maybe not.</p><p>Let me introduce some interesting issues after the switch of render engine.</p><h3>Rendering Unicode Characters Wrong</h3><p>When it comes to strings and texts. This may be a big nightmare to all developers. One feature Xterms.js always promoting is handling CJK fonts well. Actually, before introducing canvas renderer, most of this works done by browsers’ DOM render engine internally to handle various widths of Unicode characters. When the team chose to render character on our own renderer, the burden fell on Xterm.js itself. To render texts properly, Xterm.js needs to manually track width of all characters. Explicitly set width of render region is a must. 2D Canvas API is always that imperative and there is no way to stay away from it.</p><p>Surprisingly, Xterm.js has already done it before canvas render landed! It used a custom data structure to track width of a character for some resizing calculations. The only task after renderer changed is passing the character width into canvas.fillText.</p><p>Actually, character width received from terminal input are not always correct. Some characters <a href="https://github.com/Microsoft/vscode/issues/35102">consume more space than expected</a>.The truth is Xterm.js extracted some concepts from <a href="https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c">this </a><a href="https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c">wcwidth.c implementation</a>. Although the implementation covered almost all CJK and other Unicode characters with various width, it have not been modified time since 2007. During these 10 years, Emoji become prosperous. Suddenly, outdated wcwidth implementation cannot support arriving crazy overflowing characters.</p><p>But Xterm.js team did not feel contented with the situation, and later they <a href="https://github.com/sourcelair/xterm.js/pull/997">resolved the issue</a> blazing fast. If you want to know about what they did, there was nothing but <a href="https://github.com/mofux/xterm.js/blob/b3efd7e0fd1e1ebef84cfa05d741a7bbaf9441e4/src/renderer/TextRenderLayer.ts#L207">delegating up the responsibility of width calculation</a> to web browsers’ render engine. When calling ctx.measureText, the render engine measures the target text in specific canvas context, then returns a TextMatrix that stores information abount how the text would be rendered, such as width, actualBoundingBoxLeft, and alphabeticBaseline. This implementation need not to acquire any Unicode code point mapping beforehand. Just believe that all browsers do it right.</p><h3>Lack of True Color Support</h3><p>As hardware advanced, true color terminal programs are more common nowadays. The lack of real true color support become a major problems of Xterm.js. I haven’t trace to intent why the original Xterm.js supported only ANSI 256 color, but it makes sense that canvas renderer does not support true color.</p><p>There is a class ColorManager which constructs ANSI 256 color to hex color mapping table beforehand in Xterm.js v3. This eliminates dupe computations of each hex color. However, If we want to store all the true color palette, that would be combinations of 3 color channels (RGB) multiplying alpha channel, which approximately equal to 16 million of combinations! It&#39;s impossible to store that huge CharAtlas in memory simultaneously.</p><p>Thus, they use a hacky way (in <a href="https://github.com/sourcelair/xterm.js/blob/2e8410da4bf4ccc44b7277ec22a0d473565c9d13/src/Terminal.ts#L2146-L2230">Terminal.ts</a>) to make colors look like true color. The goal of this algorithm is to find the nearest color in ANSI 256 color palette. While we try <a href="https://gist.github.com/XVilka/8346728">some real tests</a> on it, we still can tell the differences without doubt. Some matching results are even so worse that they almost look like inverted colors. Many open-source projects depended on Xterm.js are eager for true color supports, including famous terminal app <a href="https://github.com/zeit/hyper/issues/2294">Hyper</a>. However, it seems that supports for true color is not the primary goal and has been remove from v3 milestones, but <a href="https://github.com/sourcelair/xterm.js/issues/484">the related discussion on Github</a> is still valuable to take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYmRQ-JtpZpnPS7Q.png" /><figcaption><em>The </em><strong><em>REAL</em></strong><em> true color in </em><a href="https://github.com/jwilm/alacritty"><em>Alacritty</em></a><em>.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZUha43drbqUx-gLq.png" /><figcaption><em>The </em><strong><em>quasi-</em></strong><em> true color in VS Code 1.17.</em></figcaption></figure><h3>Summary</h3><p>It is very lucky see that a widely used library is brave enough to make breaking changes. When I followed up the PR to read source code of Xterm.js, I almost believed that I were working with those brilliant contributors. The experience of tracing a well documented refactor process is awesome. You can learn from some surprising solutions you have never thought before. You can also learn many communicating skills in open source world. Although canvas API is not the latest web standard and Xterm.js is not a well-known project compared with React and Vue, the success of Xterm.js’ renderer refactor is worthy for learning!</p><p><em>Originally published at </em><a href="https://gist.github.com/weihanglo/8b5efd2dbc4302d123af089e510f5326"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a40f7f8792" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/source-reading-how-is-new-terminal-in-vs-code-so-fast-10a40f7f8792">How Is New Terminal In VS Code So Fast?</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts on React Native from an iOS developer]]></title>
            <link>https://medium.com/@weihanglo/thoughts-on-react-native-from-an-ios-developer-57609c33b2f6?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/57609c33b2f6</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Sun, 30 Jul 2017 14:22:30 GMT</pubDate>
            <atom:updated>2018-07-11T12:48:18.711Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*TzfT3KQK9nYWT9tP.png" /><figcaption>Photo credit: <a href="https://blog.algolia.com/">https://blog.algolia.com</a></figcaption></figure><p>About two month ago, I started making a React Native app <a href="https://github.com/weihanglo/pycontw-mobile">“PyConTW 17”</a> for the biggest annual Python conference in Taiwan (<a href="https://tw.pycon.org/">PyCon Taiwan</a>). The app is quite simple, but still took some efforts for me to build. As a complete React newbie, I would like to share some of my thoughts about React Native.</p><p><em>(written on 2017–07–30, based on React Native 0.44.2)</em></p><blockquote><strong><em>Disclaimer</em></strong><em>: I am a junior iOS developer (about 1 year experience) without any computer science degree. This article is based on my 2 weeks React Native experience developing “PyConTW 17” and React knowledge gained from my job recently.</em></blockquote><h3>What I’ve done</h3><p>Before sharing my point of view, let’s learn what features are included in this conference app:</p><ul><li>A user could view all event/talk information of the whole conference.</li><li>A user could save some favorite events for quick access (saved locally).</li><li>A user could filter events by pre-defined tags of category.</li><li>Events would update automatically if any data in database changes.</li></ul><p>As an iOS developer, you may feel familiar with these requirements. The app may be just a tabbar-based app with some customized table view to display contents. No database. No synchronization for user-generated data. Our React Native version app share with this basic anatomy mentioned above. Therefore, the UI architecture only contains some views such as list views, detail views of event/speaker, and the main app container. That’s all in this app.</p><h3>The good part</h3><h4>Shared codebase</h4><p>This project seems to only contain trivial implementation details from an veteran iOS developer’s perspective. What if you need to target at both Android and iOS in one week? Learning Android development from scratch may not be suitable with an approaching deadline, and the separation of codebase may be prone to maintenance issues in the long run. To achieve the goal, you could choose React Native in order to <strong>wrap the core logic into one codebase</strong>. No more switches between Android Studio and Xcode. React Native would give us a truly native app. That’s why React Native hypes.</p><h4>Faster development iteration</h4><p>We are all tired of write-compile-debug iteration for our daily mobile app development. With the growth of the bundle size, it would take more time to build our app (especially in Swift). React Native uses some tricks like <a href="http://facebook.github.io/react-native/releases/next/docs/debugging.html#reloading-javascript">Hot and Live Reloading</a> to refresh your simulator/emulator instantly without recompilation. That’s really an incredible time saver.</p><p>Moreover, if you choose <a href="https://github.com/react-community/create-react-native-app">Create React Native App</a> as the scaffolding tool, you can gain benefits from <a href="https://expo.io/">Expo</a> platform to test your app in real devices without any wired connection. What you need to do is scanning the QR code and coding. This is a huge leap from traditional mobile native development cycle.</p><h4>Clever devtools</h4><p>Did you remember the last time using the <strong>View Hierarchy Debugger</strong> in Xcode? This tool is very awesome for visually debugging, but sometime it’s quite laggy with complicated views hierarchy (improved in Xcode 8), and that leads to frustration. The solution React Native providing is a web-browser-like inspector for us to inspect elements on simulators. With the inspector, you can see box model, styles and even inheritance hierarchy of the selected component without long wait for the rainbow ball rotating. Additional, React Native also has a performance panel to help you achieve 60 FPS animations.</p><p>If you need more advanced debug tools, there is also a <a href="https://github.com/facebook/react-devtools">remote debugging plugin</a> available. You can <strong>download it from Chrome Web Store or Firefox Add-ons</strong>. This debugger allows inspection of React component instances, and you can also see logs from browser console.</p><p>There are still lots of tools that did not cover in this article. Either tools offered by Facebook or contribute by communities (like <a href="https://github.com/gaearon/redux-devtools">Redux Devtools</a>) are convenient for daily use. Feel free from escaping Xcode!</p><blockquote><em>To be honest, Xcode provides plenty of excellent debugging and profiling tools which are greater than those browsers have. However, they are not easy to start with, and every iOS developer I met seldom uses them.</em></blockquote><h4>Modern JavaScript</h4><p>JavaScript is very promising these years. ES2015 introduced lots of anticipating modern feature such as Promise and Generator. However, due to the diversity of browser ecosystem, if one wants to use new features to support most browser vendors, it will need to add some polyfills or transpile all code to the target version. However, the setup procedure of build environment for transpilation is annoying to some extent.</p><p>In React Native development, this is no longer a problem. All we need are done by a scaffolding tool called react-native-cli. This tool will setup a modern JavaScript development environment with all new JavaScript features. We can boldly use async/await syntax to avoid callback hell, and even use the new fetch Web API for HTTP requests. In comparison of old web-based hybrid technology such as Cordova, React Native eliminates the scary setup process and brings all pleasant stuff to live!</p><h4>Dependency management</h4><p>Another sweet point of React Native is the dependency management. <strong>CocoaPods</strong> is de facto dependency manager for Cocoa development, yet it is written in Ruby that increases costs to learn. Nowadays we get <strong>Carthage</strong> which is written in pure Swift, though it still has <a href="https://github.com/Carthage/Carthage#nested-dependencies">some issues</a> as dependencies being more complex and nested. No one want drag all dependencies of 3rd module manually.</p><p>As for React Native, we can use <strong>Npm</strong> (or <a href="https://yarnpkg.com/">Yarn</a> I recommended), one the best dependency management and ecosystem in the world. Npm reduces the painful <strong>workspace</strong> regeneration and sharing issue with CocoaPods, as well as manages dependencies with nested resolution to avoid incorrect versioning. Though the whole packages may be a little bit large, it may not be a problem for a mobile app. After all, the connection status on the internet is more strict than native app. We should be content that we do not need to download all resources on every single launch.</p><h4>Community</h4><p>There are always a strong community behind a successful open source project. So does React Native. The community of React Native is one of the most active open source communities. Developers proficient in Android or iOS create lots of useful native modules to break down the barrier between native code and JavaScript. A famous example is <a href="https://github.com/react-native-community/react-native-svg">React Native SVG</a> which implements SVG rendition with native rendering API (on iOS, it use CoreGraphics to accomplish).</p><p>Other developers coming from React community bring more new web development concepts to mobile land. For instance, unidirectional data flow, state management, component-based architecture, router patterns and many others. These concepts also have influenced back on pure native development, and invoke the reconsideration of traditional MVC/MVP/MVVM architecture. More and more talks discuss about view purification and state centralization. Some enthusiasts even started to develop a new state management module called <a href="https://github.com/ReSwift/ReSwift">ReSwift</a>, which is inspired by Redux.</p><p>The benefit of these abstractions is not only full of cool jargons but predictable, making views become testable. The most important impact on native development in my opinion is the concept of predictable unit tests, which is absent in traditional MVC architecture.</p><h3>The pain points</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yeVWONA_66OzQP4o.jpg" /></figure><h4>One codebase cannot rule them all</h4><p>If you have read the official React Native website thoroughly, you will notice that the slogan of React Native is <em>“Learn once, </em><strong><em>write</em></strong><em> anywhere”</em> instead of <em>“</em><strong><em>run</em></strong><em> anywhere”</em>. One can realize that <strong>React Native does not aim to be shareable between different platforms</strong>. Actually, Facebook suggests that developers should <a href="http://makeitopen.com/tutorials/building-the-f8-app/design/">design different components for different platforms to match platform-specified user experience</a>. For example, an Android app may not need an back button for navigations because each Android device has a physical back button.</p><p>Another issue is related to platform differences. Not all API on iOS could meet a compatible API on Android. For examples, shadowProps have no effect on Android yet Android has another elevation style to generate a shadow-like visual effect. We may also face on some bug in old buggy webview of iOS like not calling WebView#onLoadEnd after loaded. When it comes to build system, you may overwhelm by diverse toolsets for each platform. For me, I must learn groovy to write some gradle scripts which only read keystore property for app signing and submission. How painful!</p><p>As far as you dive into mobile app development, you will find that the basic API of React Native are always not enough to use. Instead, you would aware yourself stackoverflowing around and looking for other out-of-the-box libraries to use immediately. Although there are hundreds of open source libraries for cross platform React Native development, every single library is written in at least two different programming language to accomplish its purpose, and that means double knowledge and cost are included. From build system to rendering API, each platform needs specific approaches to optimize all aspects. Therefore, you shall not treat those libraries as normal JavaScript modules. Native development is that hard.</p><blockquote><em>As an iOS developer, if there is no React Native module that meets your needs, you need to tell your boss to recruit a real Android man for help, or pay you double to learn the whole new Android development stack.</em></blockquote><h4>Steep learning curve</h4><p>As a traditional mobile app developer, you are familiar with object-oriented programming. Factory pattern, adapter pattern appear all of your daily life. What if someone told you that your function is <strong>not pure</strong> enough and suggest to use <strong>monad</strong> to wrap your API? These are all functional programming buzzwords. Despite of flexibility of React Native, the <a href="https://facebook.github.io/react/docs/thinking-in-react.html">Thinking in React</a> concept makes React fit for functional programming paradigm. Most of the open source libraries built around React ecosystem conform to functional programming pattern. If you determine to adopt React Native into your development stack, it may spend additional efforts to learn with <a href="http://git.io/fp-jargons">all those jargon</a>. From a manager’s perspective, it is hard to recruit a well trained programmer equipped with functional programming skills (at least in Taiwan).</p><h4>Concurrency</h4><p>React Native uses JavaScriptCore to handle all JavaScript code, request for resources, and communicate with native code. Under the hood, all JavaScript code run in JS thread. This JS thread is a real system-level thread which would work asynchronously with the main thread (UI thread). Here is one thing you must know: <strong>UI thread and JS thread are the only two threads developers will get in an pure React Native app</strong>. That&#39;s where the problem begins.</p><p>When we wants to do some heavy computation like encryption or data transformation, all user interactions will be stuck without any feedback because all JavaScript code is run under a single-threaded JavaScript engine. That’s not acceptable for an app concerned with user experience. Though we can <a href="https://facebook.github.io/react-native/docs/performance.html#my-touchablex-view-isn-t-very-responsive">do some tricks</a> with the help of JavaScript message queue, the heavy computation still awaits there and gets ready for blocking the main thread.</p><p>On Cocoa, we have the wonderful <a href="https://en.wikipedia.org/wiki/Grand_Central_Dispatch">Grand Central Dispatch</a> (Dispatch framework in Swift 3), which abstracts thread management for us to do concurrent jobs. In React Native, if we want to manage real threads on our own, the only way is leaking abstractions. We need to write a native module creating another JSVirtualMachine and expose API to React Native. Sounds great, but also like an terrifying obstacle to those not familiar with native. You should always consider performance issue in comparison between JavaScript and native solutions (Hi Electron, I am talking to you).</p><h3>Is React Native worth learning?</h3><p>The short answer is: <strong>yes</strong>.</p><p>The long answer is: <strong>definitely yes for your next application</strong>. Learning React Native can leverage your knowledge to another level. Those impressive, promising concepts will sharpen your skills and bring great ideas to your software development knowledge. If you are still concerning about the cost of switch to React Native, here are some scenarios for you to choose React Native over native platform:</p><ul><li>Need to build this app within a short period of time.</li><li>Single purpose app like “PyConTW 17” is most suitable.</li><li>Not heavily rely on native API (sorry to HealthKit, ARKit and SiriKit).</li><li>User interface is relative simple.</li><li>Have teammate with strong native experience (we need both Android and iOS).</li><li>Your team applies <a href="https://blog.daftcode.pl/hype-driven-development-3469fc2e9b22">Hype Driven Development</a>.</li></ul><p>After all, <em>everything in life is a trade off.</em> Just ship your code and enjoy the evolving mobile app development world!</p><p><em>Originally published at </em><a href="https://gist.github.com/weihanglo/8bea3b14b617afe17314ff2482f86f0f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57609c33b2f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[試答 Cherny 所謂「最好的前端面試題」]]></title>
            <link>https://medium.com/@weihanglo/answers-to-chernys-interview-questions-ed5b35dce930?source=rss-cc5f971df1f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed5b35dce930</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[面試]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[前端]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Weihang Lo]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 14:10:17 GMT</pubDate>
            <atom:updated>2018-07-11T12:48:44.071Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>這份面試題出自<a href="https://performancejs.com/post/hde6d32/The-Best-Frontend-JavaScript-Interview-Questions-(written-by-a-Frontend-Engineer)">於此</a>，是從 <a href="https://www.reddit.com/r/Frontend/comments/6knex6/the_best_frontend_javascript_interview_questions/">/r/Frontend/</a> 連結過去的，看到如此自豪的標題和簡介，便手癢來作答。結果寫完基礎概念篇，才發現這份題目在 reddit 上被批評到體無完膚，與現代前端技術棧相差頗大。不過，一些核心概念還是挺重要的，在此分享小弟的答案，有任何錯誤，請各位不吝賜教。</p><p><em>（撰於 2017–07–26）</em></p><h3>Concepts</h3><p>Be able to clearly explain these in words (no coding):</p><h3>What is Big O notation, and why is it useful?</h3><p>Big O notation 是用來分析演算法複雜度的漸近符號，可以簡單視為<strong>運算成本（時間、空間）與輸入資料量的趨勢函數</strong>，例如 f(x) = x² + 3x + 6。當輸入資料量增大時，函數的「最高次項」最具有決定性，因此可以之表示演算法在資料量夠大時，「最多」達到怎樣的趨勢（趨勢上界），例如上例的複雜度會是 f(n) = O(n²)。（另有 Big-Theta、Big-Omega 分別描述「趨勢區間」與「趨勢下界」）</p><p>Big O 以宏觀的角度來分析演算法，並利用簡單的數學式表示，令演算法效率分析有簡明、客觀的基準。</p><h3>What is the DOM?</h3><p>全名為「Document Object Model」，是 W3C 的標準之一，定義如何將文件（XML／HTML document 等）映射至一樹狀結構中，每個節點都是一個物件，並帶有操作此 DOM node 的 API。</p><h3>What is the event loop?</h3><p>JavaScript 是單執行緒（單線程）的程式語言，任何龐大運算都可能阻塞整個程式，因此 JavaScript 設計了 <strong>message queue</strong> 配合一個不間斷的 <strong>event loop</strong> 來管理任務，當 call stack 沒有執行任何 task 時（程式閒置時），loop 便從 queue 中取第一個 message 至 call stack 調用。開發者可將 callback 加入 message queue 等待 loop 輪詢（polling），實現非同步程式，這就是 JavaScript event loop 的機制。</p><p>實際上 event loop 的概念並不僅限於 JavaScript，其他語言的 main loop 或像 iOS／macOS 的 NSRunLoop 都是建立在此概念之上。</p><h3>What is a closure?</h3><p>在某些函式（function）為一等公民（可來傳遞、當作引數）的程式語言中，<strong>閉包（closure）是「一種特殊的函式，會儲存／綁定該</strong><a href="https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping"><strong>詞法作用域（lexical scope）</strong></a><strong>下被引用的變數資訊」</strong>，如綁定閉包內被引用的外部變數，讓 closure 可以使用這些變數，這種儲綁定外部變數的行為稱為 capture，被儲存的變數一般稱 <a href="https://en.wikipedia.org/wiki/Free_variables_and_bound_variables">captured／free／bound variable</a>。</p><p>由於這些外部變數被 closure 綁定，因此可以在這些變數宣告的作用域外執行 closure 並使用這些 variables，，所以 closure 廣泛應用於程式區塊間互相傳值／通訊，例如非同步常使用的 callback function，經常會是一個 closure。近幾年函數式程式設計（functional programming）當紅，高階函式（higher-order function）的函式參數（function parameter）也是一種常見的 closure。Functional programming 另一個技法 <strong>currying</strong>（將多參函式轉換為單參函式），同樣利用了 closure 捕獲 variables 的特性。當然，最常見的 setTimeout、setInterval 就是 closure 的最佳範例。</p><p>需注意的是，由於不同語言的記憶體管理方式有差異，binding free variable 的實作也不盡相同，目前記憶體管理方式，大致上分為 <a href="https://en.wikipedia.org/wiki/Reference_counting">Reference Counting（RC）</a>與 <a href="https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)">garbage collection（GC）</a>，若是以 RC 管理記憶體的語言（如 Swift、Objective-C），需注意 reference count 在 closure 內部可能會增加，部分語言需要手動 release reference。</p><h3>How does prototypal inheritance work, and how is it different from classical inheritance?</h3><p>JavaScript 的物件導向概念是基於「原型（prototype）」而設計，有別於其他基於類別（class）的語言，其中最大的差異就是 prototype-based 的物件導向並無 class 概念。我們可將傳統的 class-based 的 class 想像成藍圖，實例（instance）是依照此藍圖創造出來（實例化，instantiation）；而 prototype 則較接近桃莉羊，概念類似於從已知實例創造出新的實例，共享（或複製）原始來源的特性。</p><p>Prototype-based 的語言雖沒有真正的 class，但會有類似建構子（constructor）的方法／函式，創建實例是，同時將原型物件的屬性／方法（property／method）複製或引用一份。例如 JavaScript 中每個物件皆有 prototype 這個原型物件，<strong>所有透過建構子實例化的實例，都可以從自身的屬性，取得該原型物件的同名的屬性</strong>。要注意的是，有些實例的屬性可能是一個引用（reference），直接指向原型物件對應的屬性，修改可能會使其他實例受影響。比較常見的做法是<strong>繼承建構子</strong>，或是<strong>複製整個原型物件</strong>。</p><blockquote><em>ES2015 提供以傳統物件導向語法 </em><em>class extends 完成繼承的語法糖，本質上仍是 prototypal inheritance，但相對門檻較低，程式碼也比較直觀。</em></blockquote><h3>How does this work?</h3><p>當一段 code 被 JavaScript 執行時，會創建新的執行上下文（execution context），在創建之初就會綁定 this 的值（還有變數與作用域鍊），接下來才執行程式碼。要知道 function 的 this 指向何者，就要了解創建 context 時是 function 如何被調用。一般來說，以下幾種狀況便可涵蓋大多數的情境。</p><p>情境 this 指向</p><ul><li>在全域直接調用一個 function：window 或 global（node）</li><li>調用物件的方法 <em>obj.method</em>：該物件</li><li>function.call／bind／apply：被綁定的物件</li><li>透過 new 調用 constructor：新創建的物件</li><li>ES6 arrow function：該詞法作用域下的 this（較直觀）</li></ul><h3>What is event bubbling and how does it work?</h3><p>JavaScript DOM Event 的傳遞會經過三個階段：</p><ul><li><strong>capture phase</strong></li><li><strong>target phase</strong></li><li><strong>bubbling phase</strong></li></ul><p>當一個事件觸發時，會從 window 往 DOM tree 傳遞，從 tree root（document）往下找，直到監聽該事件的 Event target，這個階段就是 <strong>capture phase</strong>，到達 Event target 則稱之 <strong>target phase</strong>。在這之後，event 會像冒泡泡板開始往上傳遞，傳遞到 window 為止，這就是 <strong>bubbling phase</strong>。JavaScript 的 Event listener 預設是在 bubbling phase 捕捉事件，所以當 Event Listener 沒有終止事件傳遞（Event#stopPropagation），其父元素若有監聽事件，就有機會捕捉到該事件。</p><h3>Describe a few ways to communicate between a server and a client. Describe how a few network protocols work at a high level.</h3><p><em>（這問題有點太廣，要怎麼回答⋯⋯）</em></p><p>伺服器與客戶端之間的通訊，有許多大大小小的概念與方法，以下介紹幾個前端常見的：</p><h4>HTTP</h4><p>HTTP 網路上最常見的 protocol 之一，屬 OSI 第七層 Application layer。概念是<strong>用戶端發起請求（request），伺服器端根據請求，回應（response）對應的狀態與資源</strong>。用戶端可發送不同的 request method（GET、POST 等），以不同的方式操作資源。伺服器端則可根據 request method、body、headers、session 等資訊，決定該回應什麼狀態（例如 302 Temporarily Moved）以及 response message、headers 等。</p><h4>Network Socket &amp; WebSocket</h4><p><strong>Network Socket</strong> 為一個提供程式（更精確的說是 process）間雙向溝通的網路通訊接口，通常會綁定（bind）在一個 port 上，讓 Transport Layer（TCP／UDP）與 Application Layer 得以互相辨識溝通，其他程式則透過 TCP 層，再經由 socket 實例與該 process 交換資料。也可以視 socket 為 TCP 層的封裝。<br> 受 Unix「一切皆檔案」的哲學影響，socket 通常會提供 open、write、close 等 API，甚至實作上就是一個實際檔案，因此，通常將 socket 視為 OSI 第五層 Session Layer，負責管理每個 session 對話。</p><blockquote><em>可比喻成「給予 process 專屬信箱（socket），讓其他 process 透過地址（IP）傳信給它」。</em></blockquote><p><a href="https://www.websocket.org/">WebSocket</a> 則是一個全雙工（full duplex）的通訊協議，目前已是 W3C 與 IETF 的標準之一，主要提供但不限於 web browser 與 web server 間的通訊。由於傳統的 HTTP 協議只能利用 polling 的方法模擬雙工，效能不佳，透過將 HTTP 協議升級（Upgrade）為 WebSocket，讓許多實時（realtime）的需求得以實現。<br> 目前各大主流瀏覽器皆已實作 WebSocket API，也有許多函式庫（如 <a href="https://socket.io/">Socket.io</a>）可以選用。</p><p><strong>WebSocket</strong> 與 <strong>Network Socket</strong> 雖然都稱作 socket，但差距不小，Network Socket 如前所述，是封裝 TCP 層，讓 process 有專屬接口，與 TCP 溝通，屬 Session Layer，並非一種協議，而是類似於 API 的存在； WebSocket 則是從 HTTP 協議升級的一個完整全雙工協議，有標準的 API，屬 Application Layer。</p><h4>WebRTC</h4><p><em>（先聲明，這不是 client-server 的通訊方法，但卻是近年很重要的一個 Web 標準。）</em></p><p><a href="https://webrtc.org/"><strong>WebRTC</strong></a> 是一些 API 與協議的集合，提供瀏覽器透過 plugin-free 的 P2P 連線（browser-to-browser），達成 Real-Time Communications（RTC）的功能，也就是說，瀏覽器間可不透過伺服器，直接穿透 firewall 交換訊息。WebRTC 推行多年，直到今年 Apple 才在 2017 WWDC 宣告下一版本的 Safari／iOS Safari 將全面支援 WebRTC，因此，可大膽預測 WebRTC 會逐漸取代傳統 P2P 視訊底層的技術，甚至<a href="https://www.zhihu.com/question/25497090">有望成為直播技術選擇</a>之一。</p><p>WebRTC 除了傳送音訊與視訊，也可傳送<strong>任意資料</strong>，場景看似與 WebSocket 重複，實際上仍有差異。從傳輸協議來看，WebSocket 封裝 TCP，丟失封包會重傳；WebRTC 底層為 RTP，可接受封包丟失。從對話架構來看，WebSocket 為 client-server 主從式的通訊架構；WebRTC 則是 P2P、client-to-client 的實時通訊。</p><h4>TCP/IP</h4><p>TCP 與 IP 是兩個不同的通訊協議，TCP 為 OSI Transport Layer 的協議，主要負責<strong>提供可靠、錯誤校正的傳輸資料，封包若丟失，TCP 會嘗試重傳</strong>；IP 則是位於 Network Layer 的協議，主要功能為<strong>尋找主機位置，封裝資料，再從來源路由（routing）到目標主機</strong>。</p><p>由 TCP／IP 等網際網路協議組成的網路架構通常稱為 <strong>Internet protocol suite</strong>，被視為簡化版的 OSI 模型，也是目前最主流的網路架構。</p><h3>What is REST, and why do people use it?</h3><p><em>（聲明：本人錯過 SOAP 的年代，實務上只使用過 RESTful 架構）</em></p><p><strong>REST</strong>，全名為 <strong>REpresentational State Transfer</strong>，是眾多網路軟體架構中的一種，以結構清晰簡潔著稱，目前主流的網路服務都以此風格架設，大致實作概念為：</p><ul><li>所有資源以 URI 表示。（resource-oriented）</li><li>資源可以不同的形式表現（例如 XML 或 JSON），取決於客戶端環境、headers 設定等。</li><li>使用標準 HTTP request method（GET、POST、PUT、DELETE 等）對資源進行不同的操作。</li></ul><p>由於透過標準 HTTP protocol 實現 RESTful 架構，一切 request 都是無狀態（stateless），因此有許多優點：</p><ul><li>stateless，可以利用 cache 機制。</li><li>stateless，容易用各種工具調試（如 <a href="https://curl.haxx.se/">cURL</a>、<a href="https://httpie.org/">httpie</a>）。</li><li>每個 request 都獨立，耦合性低。</li><li>利用 URI，統一 API 接口定義。</li></ul><blockquote><em>因為 RESTful 以資源為導向的風格，後端常會為了日益增長的需求，開發了許多大同小異的 API，新興的 </em><a href="https://gist.github.com/weihanglo/graphql.org"><em>GraphQL</em></a><em> 就是為了對付這類問題，日益發展起來。</em></blockquote><h3>My website is slow. Walk me through diagnosing and fixing it. What are some performance optimizations people use, and when should they be used?</h3><p><em>（講一個 slow 是能看出什麼毛喔⋯⋯）</em></p><p>所謂網頁很慢，有兩大類別，一是 client 端效能的問題，最容易觀察到的現象就是<strong>動畫掉幀</strong>；另一個則是<strong>網路請求太久</strong>。我們先談動畫掉幀。</p><h4>動畫掉幀</h4><p><strong>動畫掉幀</strong> 就是指動畫 FPS 未達到人眼視覺暫留的時間間隔，一般以 60 FPS 為分水嶺，低於 60 FPS 就會產生卡頓的感覺。究其原因，不外乎運算量過大，擠壓到動畫觸發的時間點，瀏覽器自動 skip 到下一個 frame。一般有兩個思考方向：</p><ol><li>是否觸發過多的 reflow（layout）？</li><li>動畫相關的的 JavaScript code 效能是否低落，太多複雜運算？</li></ol><p>關於 <strong>減少 reflow（layout）</strong>，這裡有幾個關於 CSS 的小撇步：</p><ul><li>儘量使用 transform 替代操作 width、top 等 style，減少 reflow。</li><li>若必需更改到 width 等 style，可嘗試使用絕對座標 position: absolute。</li><li>適量使用 will-change 通知瀏覽器準備動畫所需資源</li><li>觸發 GPU 運算加速渲染（通常添加 transform: translateZ(0) 來觸發）。</li><li>不要任意更改 flex item 的寬高與座標，會增添非常多額外的運算。</li><li>善用瀏覽器開發者工具檢視動畫在哪裡掉幀，並即時更改 styles，預覽修正結果，降低迭代成本。</li></ul><p>很多時候，reflow，和 <strong>JavaScript code performance</strong> 脫離不了干係，我們仍有許多法門提升程式碼效能。</p><ul><li>首先，當然是檢視演算法本身有沒有優化空間，能不能降低複雜度，是否允許以空間換時間。</li><li>經常觸發的動畫或運算（例如 window resizing），是否可以設置 throttle／debounce。</li><li>承上，善用 requestAnimationFrame 讓與動畫直接相關的程式碼之觸發間隔與動畫同步。</li><li>合併 DOM 操作（batch），降低 DOM tree 改變次數（例如 React 的 Virtual DOM）。</li><li>將 synchronous 的運算改為 asynchronous（需注意架構與維護性）。</li><li>若是必要的龐大運算（如加解密），可放置到 web worker，將 main thread 留給 UI。</li><li>一定要了解<a href="https://gist.github.com/paulirish/5d52fb081b3570c81e3a">哪些行為會造成 reflow</a>。</li></ul><h4>網路請求</h4><p>上述動畫掉幀的「慢」，較屬使用者互動的 UI 層，Web App 另一個瓶頸是網路請求（request），舉凡下載圖片，請求 CSS JavaScript 等等與 request 相關的操作，很容易因為資源取得過慢，造成使用者觀感欠佳。解決的方法不少，重點大多在減少 request 數量，以及善用快取，以下舉一些常見作法。</p><ul><li>JavaScript CSS 最小化與打包。（已有許多構建工具可用，例如 gulp、webpack 或 rollup）</li><li>按需加載（on-demand loading），例如滾動到 visible area 才下載圖片，或需要時再載入 script。</li><li>以 sprite 的方式組合 assets，減少 request 數量。</li><li>善用 browser cache、local storage 等技術，讓資料可即時取得。</li><li>開啟 <a href="https://en.wikipedia.org/wiki/HTTP/2_Server_Push">HTTP/2 server push</a> 等機制。</li><li>多利用 placeholder／thumbnail 等 UI 設計，降低要求資源的等待感。</li></ul><p>其實還有非常多優化效能的作法與手段，這裡暫時打住。</p><h3>What frameworks have you used? What are the pros and cons of each? Why do people use frameworks? What kinds of problems do frameworks solve?</h3><p>很抱歉，本人的前端資歷沒這麼深厚，backbone、Angular 1／2／4 都沒深入研究，只用過 Facebook 出品的 React。以下針對 React 簡單分析。</p><h4>Pros</h4><ul><li>大公司出品，該公司主要的產品皆採用之（Facebook、Instagram），不易突然終止。</li><li>廣受業界泛用，是近幾年新產品的主流框架。</li><li>社群蓬勃，生態豐富，文檔甚多，甚至有不少 Conference 專門討論 React。</li><li>組件化開發，讓不同專案的元素複用變可能。</li><li>Virtual DOM 架構，減少不必要的 DOM manipulation。</li><li>One-way binding 的資料流，容易設計架構清楚的 app。</li><li>利用 JSX 與 ES6，釋放 JavaScript 最大能量，不必與蹩足的模板引擎溝通。</li><li>Renderer 與 React Core 分離，<strong>Learn once, write any where</strong> 不再是夢（例如 React Native）。</li><li>有完整豐富的生命週期函式供調用。</li></ul><h4>Cons</h4><ul><li>開發環境建構複雜，不易上手。（社群有許多 configure-free 的 starter kit／boilerplate 可選用）</li><li>Component-based 的概念顛覆傳統 template 的思維，需要較多學習成本。</li><li>One-way binding 也非傳統前端開發人員熟悉的架構。</li><li>偏向函數式程式設計的理念讓 OOP 開發者較吃不消。</li><li>組件化的架構造成某些 data source 需層層傳遞，才能到達實際呈現資料的 component，距離過遙。</li><li>承上，社群提供許多 State management 供選擇（Redux、Flux、MobX 等），但都是額外的學習成本。</li></ul><p>人們使用框架的理由很多，可能是習慣這個開發流程、覺得很潮，或是真的能提升生產力。但在導入框架之前，真的完全理解「框架」是什麼嘛？所謂框架（Framework），和函式庫（Library）的差異可一言以蔽之：</p><blockquote><strong><em>With great power comes great responsibility.</em></strong></blockquote><blockquote><em>- </em>Ben Parker</blockquote><p>一個強大的函式庫如 jQuery、RxJS，不會有太多限制，如同一間圖書館，靜待人們去了解、學習，而後應用。而框架就好比設計完善的課程，按部就班即可有不錯的成果，倘若欲突破框架限制，仍要自己去發掘知識。本人認為兩者思維上的差異就是 <strong>Responsibility</strong>，以 React 來說，設計者不希望開發者直接操作太多 DOM tree ，所以 access DOM tree 便須透過麻煩的 ref，降低開發者濫用 DOM tree 的機會，React 因此可好整以暇地管理 DOM tree，權責分明。</p><p>引入一個框架，最大的好處就是<strong>開發會遵循明確的規範</strong>，雖然可操作空間被限制了，但也相對責任也輕許多，只要了解該框架，大致上就能理解專案的邏輯，可讀性提昇不少。對我來說，成功的框架，必定有明確清楚的規範，同時也釋放權力給勇於自己負擔責任的開發者，這就是框架最核心的價值之一（當然，效能、延伸性、發展性等等也很重要），也是我們期許臺灣教育能達到的高度。</p><h3>Thoughts after completion</h3><p>這份面試題花了不少時間撰寫，著實問到許多基礎觀念，但並沒有完全切中前端工程的核心或是趨勢，畢竟前端學習點太多了，每個專案碰到的技術可能大相逕庭，例如做 Web Game 的 很懂WebGL，但 CSS 可能不熟。因此，我認為好的題目不僅要能檢核面試者的實力，更要能體現其對前端領域的熱情，例如下列題目：</p><ul><li>如何實現 SPA 的 router？（理解瀏覽器如何處理 URL，或是有熱情去理解開源的 router library）</li><li>什麼是 Critical rendering path？HTML 文件如何被解析渲染？（熟悉瀏覽器解析渲染的途徑，並知道如何優化）</li><li>Webpack、Rollup 這些構建工具如何影響前端工程？和 Gulp、Grunt 有啥差異？（知道如何選擇工具，而非追流行）</li><li>如何管理維護 CSS 命名，並相容不同瀏覽器？（知道目前各大主流管理 CSS 的方式，畢竟 CSS 很容易變成一坨屎）</li><li>何謂 CORS？何謂 CSRF？（對網路資安至少有點基礎知識）</li><li>什麼是 Web Components？為什它沒有像 Vue 或 React 一樣火熱？（理解 Web 技術動態，並瞭解流行框架的優勢）</li><li>如何實現簡單的 Offline web app？介紹一下相關的技術？（知道並能應用 localStorage 等相關知識）</li></ul><p>其實上述題目小弟我有些也是一知半解，但我認為面試就是要找<strong>未來</strong>能合作的夥伴，工作熱忱、對未來的洞察力，是否能愉快合作，遠比當下的實力來得重要。感謝讀完這篇文章，希望能對各位有幫助，如果有什麼錯誤，歡迎寄信或直接留言！</p><p><em>Originally published at </em><a href="https://gist.github.com/weihanglo/09629661211c0f5614a84d64cde5fffb"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5b35dce930" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>