将对象的所有键转换为小写的最佳方法(最有效)是什么? [英] What's the best way (most efficient) to turn all the keys of an object to lower case?

查看:31
本文介绍了将对象的所有键转换为小写的最佳方法(最有效)是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了

function keysToLowerCase (obj) {
  var keys = Object.keys(obj);
  var n = keys.length;
  while (n--) {
    var key = keys[n]; // "cache" it, for less lookups to the array
    if (key !== key.toLowerCase()) { // might already be in its lower case version
        obj[key.toLowerCase()] = obj[key] // swap the value to a new lower case key
        delete obj[key] // delete the old key
    }
  }
  return (obj);
}

但我不确定 v8 会如何处理它,例如,它真的会删除其他键还是只会删除引用而垃圾收集器稍后会咬我?

But I'm not sure how will v8 behave with that, for instance, will it really delete the other keys or will it only delete references and the garbage collector will bite me later ?

另外,我创建了 这些测试,希望您能添加你在那里的答案,这样我们就可以看到它们是如何匹配的.

Also, I created these tests, I'm hoping you could add your answer there so we could see how they match up.

编辑 1:显然,根据测试,如果我们不检查密钥是否已经是小写字母,它会更快,但除了更快之外,它会因为忽略这一点而只创建新的小写密钥而造成更多混乱吗?垃圾收集器会对此感到满意吗?

EDIT 1: Apparently, according to the tests, it's faster if we don't check if the key is already in lower case, but being faster aside, will it create more clutter by ignoring this and just creating new lower case keys ? Will the garbage collector be happy with this ?

推荐答案

最快的 我想如果你创建一个新对象:

The fastest I come up with is if you create a new object:

var key, keys = Object.keys(obj);
var n = keys.length;
var newobj={}
while (n--) {
  key = keys[n];
  newobj[key.toLowerCase()] = obj[key];
}

我对 v8 的当前内部工作不够熟悉,无法给你一个明确的答案.几年前,我看到一个视频,其中开发人员谈论对象和 IIRC它只会删除引用并让垃圾收集器处理它.不过那是几年前的事了,就算那时候是这样,现在也不需要这样了.

I'm not familiar enough with the current inner working of v8 to give you a definitive answer. A few years ago I saw a video where the developers talked about objects, and IIRC it will only delete the references and let the garbage collector take care of it. But it was years ago so even if it was like that then, it doesn't need to be like that now.

以后会咬你吗?这取决于你在做什么,但可能不是.创建短期对象是很常见的,因此代码经过优化以处理它.但是每个环境都有其局限性,也许它会咬你.您必须使用实际数据进行测试.

Will it bite you later? It depends on what you are doing, but probably not. It is very common to create short lived objects so the code is optimized to handle it. But every environment has its limitations, and maybe it will bite you. You have to test with actual data.

这篇关于将对象的所有键转换为小写的最佳方法(最有效)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆