首页 > 解决方案 > 将 window.location.href 存储在 const 中进行多次比较或直接检查是否更快?

问题描述

将 window.location.href 存储在 const 中以检查是否包含多个字符串是否更快,

   const fullUrl = window.location.href;

 function checkUrlContains() {
   return fullUrl.indexOf("string1") > 1 || fullUrl.indexOf("string2") > 1  || fullUrl.indexOf("string3") > 1 || fullUrl.indexOf("string4") > 1
 }

还是直接检查window.location.href?

     function checkUrlContains() {
   return window.location.href.indexOf("string1") > 1 || window.location.href.indexOf("string2") > 1  || window.location.href.indexOf("string3") > 1 ...
 }

谢谢

标签: javascriptperformance

解决方案


有时“薄”的书是最好的。例如,编程风格的要素。 您将在其中阅读:

"Don't 'diddle' code to make it faster -- find a better algorithm."

而且:“不要假设算法‘太慢’,除非你可以通过实际的分析措施证明它太慢以及它在哪里。在你的情况下,源代码更改可能不会使任何可衡量的性能上的差异,但它可能会使你的代码更难被下一个跟随你脚步的程序员“立即理解”。唯一(这些天)你应该认真关注这些事情的时间是当分析结果证明这一点时- 或者 - 那是一个真正的“热点”。否则,只需尽可能清晰明了地编写代码,当然要非常确定它可以工作!


推荐阅读