UTF-8、UTF-16和UTF-32之间有什么区别?

我知道它们都将存储Unicode,并且每个都使用不同的字节数来表示一个字符。选择一个比另一个有优势吗?


当前回答

我做了一些测试来比较MySQL中UTF-8和UTF-16之间的数据库性能。

更新的速度

utf - 8

utf - 16

插入的速度

删除速度

其他回答

UTF-8在ASCII字符代表文本块中的大部分字符的情况下具有优势,因为UTF-8将这些字符编码为8位(像ASCII一样)。它的另一个优点是只包含ASCII字符的UTF-8文件具有与ASCII文件相同的编码。

在ASCII不占主导地位的情况下,UTF-16更好,因为它主要每个字符使用2个字节。UTF-8将开始对高阶字符使用3个或更多字节,而UTF-16对大多数字符仅使用2个字节。

UTF-32将在4字节内涵盖所有可能的字符。这使得它非常臃肿。我想不出使用它有什么好处。

Unicode是一个标准,关于UTF-x,你可以把它看作是一个技术实现,用于一些实际目的:

UTF-8 - "size optimized": best suited for Latin character based data (or ASCII), it takes only 1 byte per character but the size grows accordingly symbol variety (and in worst case could grow up to 6 bytes per character) UTF-16 - "balance": it takes minimum 2 bytes per character which is enough for existing set of the mainstream languages with having fixed size on it to ease character handling (but size is still variable and can grow up to 4 bytes per character) UTF-32 - "performance": allows using of simple algorithms as result of fixed size characters (4 bytes) but with memory disadvantage

简而言之,使用UTF-16或UTF-32的唯一原因是分别支持非英语和古代脚本。

我想知道为什么有人会选择非utf -8编码,因为它显然对web/编程更有效。

一个常见的误解-加后缀的数字不是它的能力的指示。它们都支持完整的Unicode,只是UTF-8可以用一个字节处理ASCII,所以对CPU和互联网来说更有效/更不容易损坏。

一些不错的阅读:http://www.personal.psu.edu/ejp10/blogs/gotunicode/2007/10/which_utf_do_i_use.html 和http://utf8everywhere.org

根据您的开发环境,您甚至无法选择字符串数据类型将在内部使用什么编码。

但是对于存储和交换数据,我总是使用UTF-8,如果你有选择的话。如果您的数据主要是ASCII数据,这将为您提供最少的数据传输量,同时仍然能够编码所有内容。优化最小的I/O是现代机器的发展方向。

在阅读完答案后,UTF-32需要一些爱。

C#:

Data1 = RandomNumberGenerator.GetBytes(500_000_000);

sw = Stopwatch.StartNew();
int l = Encoding.UTF8.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-8: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.Unicode.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"Unicode: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.UTF32.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-32: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.ASCII.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"ASCII: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

UTF-8—经过9.939秒-大小473,752,800

Unicode—消失0.853秒-大小2.5亿

UTF-32—消失3.143秒-大小125,030,570

ASCII—经过2.362秒-大小500,000,000

Utf-32——丢麦克风