Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

function cache #3

Open
JeffKko opened this issue Aug 17, 2018 · 0 comments
Open

function cache #3

JeffKko opened this issue Aug 17, 2018 · 0 comments

Comments

@JeffKko
Copy link
Owner

JeffKko commented Aug 17, 2018

cache 的型別

分別嘗試兩種看起來適合的型別

  • 原生 Object
    cache[testKey] //object 的取值方法
  • ES6 Map
    cacheMap.get(testKey) // map 的取值方法

結果:

ops/sec 表示每秒運算的次數

  • cache 10筆資料

    object x 20,175,513 ops/sec ±2.05% (66 runs sampled)
    map x 7,007,436 ops/sec ±4.15% (69 runs sampled)
  • cache 1000筆資料

    object x 20,268,662 ops/sec ±1.62% (65 runs sampled)
    map x 7,480,171 ops/sec ±0.70% (73 runs sampled)

object 的效能大概是 map2.5 倍 ,而 cache 筆數多寡並不會對效能造成影響

參數序列化

因為參數有可能是 object, array 等形式,必須藉由 JSON.stringify 當參數序列化

function memorizeFunc(...args) {
  return JSON.stringify(args)
}

memorizeFunc(123, { a : 3 }) //"[123,{"a":3}]"

目前 cache function 大致上可以寫成這樣

function memorizeFunc(...args) {
  let key = JSON.stringify(args)
  if( key in cache ) {
    return cache[key]
  } else {
    let random = getRandomString(1000)
    cache[key] = random
    return random
  }
}

分別對 1個參數、2個參數、3個參數測試

1 param x 978,054 ops/sec ±5.29% (68 runs sampled)
2 params x 1,177,433 ops/sec ±0.70% (89 runs sampled)
3 params x 1,072,089 ops/sec ±0.84% (91 runs sampled)

優化參數

避免每次執行 JSON.stringify 造成性能消耗,我們先優化只有一個參數的情況

function memorizeFunc(...args) {
  let key

  if(args.length === 1) {
    [key] = args
  } else {
    key = JSON.stringify(args)
  }

  if( key in cache ) {
    return cache[key]
  } else {
    return cache[key] = getRandomString(1000)
  }
}

結果:

獲取單個參數的效能提升為多參數的 4倍 左右

1 param x 2,751,567 ops/sec ±9.19% (60 runs sampled)
2 params x 662,869 ops/sec ±9.89% (54 runs sampled)
3 params x 708,058 ops/sec ±0.90% (83 runs sampled)
@JeffKko JeffKko added the Javascript javascript label Feb 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant