問題描述
我想出了
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.
這篇關于將對象的所有鍵轉換為小寫的最佳方法(最有效)是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!