如何計算哪一種程式的效能比較好
|
|
performance.now()
- 列印出執行時間差
|
|
- 不同機器跑出來的時間不同誤差
- 同樣的機器跑同樣的程式也會有誤差
- 計算時間的測量本身也會有誤差
Big O 比時間更好衡量效能的指標
- is a way to formalize fuzzy counting
- how the runtime of an algorithm grows as the inputs grow
- algorithm is o(f(n)) if the number of simple operations the computer has to do
- algorithm is eventually less than a constant times f(n) as n increases
時間複雜度
- constant/linear/quadratic
|
|
- arithmetic operations are constant
- variable assignment is constant
- accessing elements in an array(by index) or object(by key) is constant
- in a loop, the complexity is the length of the loop times the complexity of whatever happens inside of the loop
- 趨近無限大,常數可忽略,只看次方最大的
- 巢狀迴圈看要跑的次數,若為常數時間複雜度不會增加
空間複雜度: 使用記憶體的量
- 基礎型別空間複雜度是 O(1)
- n 長度的字串空間複雜度是 O(n)
- n 個元素陣列跟 n 個 keys 的物件等 ref types 通常是 O(n)
|
|
Big O of objects
- Fast, but no order
- Most constant
|
|
Big O of arrays
- When you need order and fast access
|
|
what an algorithm is:
- A PROCESS OR SET OF STEPS TO ACCOMPLISH A CERTAIN TASK
- devise a plan to solve algorithms
- compare and contrast a problem solving patterns including frequency counters, 2 pointer problem and divide and conquer
problem solving
understand the problem
-
can i restate the problem in my own words? a add b
-
what are the inputs that go into the problem ints? floats? what about string of large numbers
-
what are the outputs that should come from the solution to the problem int? float? string?
-
can the outputs be determined by the inputs?( do i have enough info to solve the problem)
-
how should i label the important pieces of data that are a part of the problem
explore concrete examples
- user stories
- start with simple examples -> complex
- empty inputs/ invalid inputs
|
|
- 可以問:需要回傳不在單字內的字母數量嗎
- “my phone number is 191231” // 需要數空白嗎 大小寫敏感嗎 數字忽略嗎
- () “” 回傳 null undefined?
break down problem
- 寫下步驟,幫助了解整體規劃
|
|
solve or simplify
- 先做出核心邏輯,找出 pattern 再處理複雜的
|
|
loop back and refactor
- 結果正確嗎
- 有其他種寫法嗎
- 可以一看就懂嗎
- 可以複用在其他情境嗎
- 可以優化效能嗎
- 有其他重構或優化的方法嗎
- 其他人怎麼解的
|
|
- 優化版
|
|