数字比较比字符串比较更快? [英] Is number comparison faster than string comparison?

查看:369
本文介绍了数字比较比字符串比较更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说哈希(即将字符串或对象转换为数字)用于字符串等,因为比字符串更容易比较数字。如果是,那是什么原因?

I heard that hashing (ie converting a string or object to a number) is used for strings and such because it is easier to compare numbers than strings. If true, what is the reason for this ?

推荐答案

这不一定是这种情况,但大多数情况下可能就是这种情况。

This is not necessarily the case, but probably the case most of the time.

考虑以下情况:

我想比较字符串apples与oranges 。如果我只想确定apples==oranges,我只需要比较每个字符串的第一个字符:'a'!='o'=>apples!=oranges。如果我对字符串进行散列然后进行比较,那么它会慢得多,因为在比较结果整数之前我必须解析两个字符串并将它们反馈到散列算法中。

I want to compare the string "apples" vs. "oranges". If I only want to determine "apples" == "oranges", I need only compare the first character of each string: 'a' != 'o' => "apples" != "oranges". If I hash the string and then do the comparison, it is significantly slower as I have to parse both strings and feed them into a hashing algorithm before comparing the resultant integers.

但是,如果我需要多次进行这种比较,也许我将橘子与猩猩进行了大量的比较,那么如果我将所有字符串都哈希一次并对整数进行多次比较,那么它就会解决快点。这是哈希映射所基于的原则。

If, however, I need to do this comparison many times, and perhaps I'm comparing "oranges" to "orangutans" a lot, then if I hash all the strings once and do the comparisons of integers many times, it will work out faster. This is the principle that a hash map is based on.

但是,注意,散列字符串对于直接等于比较很有用,它无法确定字符串是否在词汇上更大或者小于彼此,因此通过散列方法不可能排序字符串。 (这就是为什么Java中的HashMap是无序的。)

Note, however, that hashing a string is useful for direct equals comparisons, it cannot determine if strings are lexigraphically greater or less than each other, and so ordering strings is not possible via the hashing method. (This is why HashMap in Java is unordered).

这篇关于数字比较比字符串比较更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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