Performance of if-else, switch or map based conditioning

前端 未结 3 1763
Happy的楠姐
Happy的楠姐 2020-12-12 14:57

I was wondering about the performances of the following implementations of conditional structs in javascript.

Method 1:

 if(id===\         


        
相关标签:
3条回答
  • 2020-12-12 15:12

    You can always do a jsPerf test yourself. However, in general a lookup table is the fastest way to access data. That would be (3) in your snippets. Also, switch/case is almost always faster than if-else. So the order for your example would be

    (3) -> (4) -> (2) -> (1)

    0 讨论(0)
  • 2020-12-12 15:25

    Just thought I'd add this as a possible consideration. I came across this doing research on this very question... http://davidbcalhoun.com/2010/is-hash-faster-than-switch-in-javascript

    It takes different engines and browsers into account.

    0 讨论(0)
  • 2020-12-12 15:27

    According to this JSBen.ch test, the switch setup is the fastest out of the provided methods (Firefox 8.0 and Chromium 15).

    Methods 3 and 4 are slightly less fast, but it's hardly noticeable. Clearly, the if-elseif method is significantly slower (FireFox 8.0).

    The same test in Chromium 15 does not show significant differences in performance between these methods. In fact, the if-elseif method seems to be the fastest method in Chrome.

    Update

    I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

    If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.

    0 讨论(0)
提交回复
热议问题