在数组中搜索还是在开关中搜索?对于替换密码

发布于 2024-11-13 09:09:51 字数 266 浏览 1 评论 0原文

我正在通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

就此别过 2024-11-20 09:09:51

为什么需要搜索?只需有一个由 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.)

森林很绿却致人迷途 2024-11-20 09:09:51

哪一个更快取决于很多因素:编译器的优化(您必须查看程序集才能知道它的作用)以及如何设置数组。

如果性能确实很重要,并且由于这两种解决方案实施起来都相当简单,那么我会实施它们并在尽可能真实的设置中对它们进行基准测试,以找出哪一个更快。

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.

别忘他 2024-11-20 09:09:51

当然,足够智能的编译器有可能将开关优化为查找,这比二分搜索更快。但您可以自己进行优化并获得简短的代码:

char alphabet[] = {
    'Z', 'E', 'B', 'R', 'A', 'S', 'C', 'D', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'T', 'U', 'V', 'W', 'X', 'Y'
};
// now you can get the ciphertext for a single uppercase character with:
alphabet[ch - 'A'];

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:

char alphabet[] = {
    'Z', 'E', 'B', 'R', 'A', 'S', 'C', 'D', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'T', 'U', 'V', 'W', 'X', 'Y'
};
// now you can get the ciphertext for a single uppercase character with:
alphabet[ch - 'A'];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文