在数组中搜索还是在开关中搜索?对于替换密码
我正在通过 C++ 中的替换来编码经典密码,使用 ASCII 中的所有可打印字符,我想知道哪个更快?数组中的搜索(编辑:非关联搜索,就像 letters[] = {'a', 'b', ...);
(线性或二进制)或 switch 语句?编译器可以优化这个开关,不是吗?也许区别在于内存使用情况?我的选择是开关,虽然代码更大,但也许我遗漏了一些东西。
(也许这个问题看起来很主观,但我认为这是选择一种或另一种方式的客观原因。对不起我的英语)。
I'm coding a classical cipher by substitution in C++, using all the printable characters in ASCII, and I'm wondering which is faster? A search in an array (edit: a non associative one, just something like letters[] = {'a', 'b', ...);
(linear or binary) or a switch statement? The compiler can optimize the switch, doesn't it?. Maybe the difference is the memory usage? My choice is the switch, although the code is bigger, but maybe I'm missing something.
(Perhaps this question seems subjective, but I think would be objective reasons to choose one or another way. And sorry for my English).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么需要搜索?只需有一个由 ASCII 字符索引的 128 个条目的数组即可。这基本上就是编译器对你的开关所做的事情。 (您可以减去 32 并使用 96 个条目的数组,从而节省不可打印的空间。)
Why do you need a search? Just have a 128-entry array indexed by your ASCII character. That's basically what the compiler does with your switch. (You could subtract 32 and use a 96 entry array, thus saving the space used by the non-printables.)
哪一个更快取决于很多因素:编译器的优化(您必须查看程序集才能知道它的作用)以及如何设置数组。
如果性能确实很重要,并且由于这两种解决方案实施起来都相当简单,那么我会实施它们并在尽可能真实的设置中对它们进行基准测试,以找出哪一个更快。
Which one is faster depends on a lot of factors: your compiler's optimization (you'd have to look at the assembly to know what it does) and how you'd set your array up.
If performance is really important, and as both solutions are likely to be fairly simple to implement, I'd implement them both and benchmark them in an as-real-as-possible setup to find out which one is faster.
当然,足够智能的编译器有可能将开关优化为查找,这比二分搜索更快。但您可以自己进行优化并获得简短的代码:
There's certainly a chance that a sufficiently smart compiler could optimize the switch to be a lookup, which would be faster than a binary search. But you could do that optimization yourself and get short code: