javascript - indexOf 是否比尝试索引对象慢?
问题描述
我对性能一无所知。但是,如果someArray.includes(someString)
必须搜索整个数组,尝试查找对象的索引会更直接(因此更快,代码也更少)?
// create an array of number strings
const arr = Array(100).from(n => n.toString());
// find whether a string is in the array
const isStringInArr_includes_true = arr.includes("50"); // true
const isStringInArr_includes_false = arr.includes("500"); // true
// instead of creating an array, create an object with the array items as keys
// EDIT: actually you can just use the array itself
// and look up the string as a key
const isStringInArr_lookup_true = !!arr["50"]; // !!("50") === true
const isStringInArr_lookup_false = !!arr["500"]; // !!(undefined) === false
显然,这只适用于字符串数组。
解决方案
推荐阅读
- sql - 从case语句oracle sql中按Count捕获条件语句组
- python - 从dict递归设置对象属性
- arrays - Julia,根据概率执行替换
- java - 如何实现 Unity 风格的 GetComponent
JavaFX 中的 () 函数? - inno-setup - 在 Inno Setup 脚本中将一个很长的字符串参数拆分为多行
- r - 使用 ifelse 基于日期范围的新字符值
- angular - @ViewChild 返回未定义。我无法访问模式内的轮播 ElementRef
- bash - 在 makefile 中默认环境变量
- google-app-engine - 如何找到两年前部署的谷歌应用引擎源代码
- node.js - ECONNRESET(Nodejs net.Socket)后重新连接到套接字的正确方法