使用对象字面量而不是 switch 语句
switch 和 if/else 语句中有很多关于最佳实践的讨论和评论.我看到有人说我们都应该在可能的情况下使用对象字面量而不是开关.
There is a lot of discussions and comments about best practices in switch and if/else statements. I have seen people saying that we all should use object literal instead of switch when it is possible.
所以我已经复制了这个案例,我经历了一个小而简单的测试切换:
So I've reproduced this case and I went trough a little and simple test between a switch :
(function(test){
var bar;
switch(bar) {
case 1:
bar = 'red';
break;
case 2:
bar = 'blue';
break;
case 3:
bar = 'yellow';
break;
case 4:
bar = 'green';
break;
case 5:
bar = 'black';
break;
}
return bar;
})(5);
并通过对象字面量传递:
and passing trough an object literal :
(function(test){
return { 1: 'red', 2: 'blue', 3: 'yellow', 4: 'green', 5: 'black' }[ test ];
})(5);
在运行这个 test 之后,显然 switch 语句比调用测试的语句要快对象字面量中的值.
After running this test, it seems evident that the switch statement is faster than calling the tested value in an object literal.
我的测试错了吗?在这种情况下使用一种或另一种方法之前我应该考虑什么?或者也许我看到的关于这个主题的固执己见的评论是错误的,我不应该试图绕过基本面......
Is my test wrong ? What should I consider before using one or another method in this case ? Or maybe opinionated comments I've seen about this subject are just wrong and I should not try to bypass fundamentals...
推荐答案
您可能会看到规模效应:switch 语句是 O(n)
,而哈希表查找(大概使用在对象字面量中查找方法)是(摊销的)O(1)
.但是 Big-O 度量只能准确地描述性能如何在真正的大输入上扩展.在您的测试中,五个 if
语句比哈希表查找更快也就不足为奇了.
You're likely seeing effects of scale: A switch statement is O(n)
, while a hash table lookup (presumably used to find methods in object literals) is (amortized) O(1)
. But Big-O measures only accurately describe how performance scales over really big inputs. In your test, it's not surprising that five if
statements are faster than a hash table lookup.
所以基本上:你将有多少个键?如果你只有五个键,你每次查找平均会命中 2.5 个,你已经证明这比单个哈希表查找.但是如果你有 500 个呢?这是平均 250 个 if
语句 - 仍然与 单个 哈希查找相比.哈希表(对象字面量)方法在这一点上几乎肯定会更好.
So basically: How many keys are you going to have? If you've only got five keys, you'll hit on average 2.5 per lookup, which you've shown to be faster than a single hash table lookup. But what if you have 500? That's an average of 250 if
statements - still versus a single hash lookup. The hash table (object literal) approach is almost assuredly better at that point.
但最终的答案是什么?每个人都讨厌听到这个,但这是唯一权威的方法:使用您的实际生产代码进行基准测试.这很痛苦,但你肯定知道.
But the ultimate answer? everybody hates to hear this, but it's the only authoritative way: Do the benchmark with your actual production code. It's a pain, but then you know for sure.
希望有帮助!
PS:这是抛开所有编码风格偏好的考虑,但我真的不想进入那个......
PS: This is leaving aside all considerations of coding style preference, but I really don't want to get into that...
相关文章