用于一般协议消息交换,可以容忍一定的丢包。UDP比TCP效率高多少?


当前回答

UDP比TCP快,原因很简单,因为它不存在允许连续数据包流的确认数据包(ACK),而不是使用TCP窗口大小和往返时间(RTT)来确认一组数据包的TCP。

要了解更多信息,我推荐简单但非常容易理解的Skullbox解释(TCP vs. UDP)

其他回答

网络的设置对于任何测量都是至关重要的。如果您通过本地机器上的套接字或与世界的另一端进行通信,则会产生巨大的差异。

我想在讨论中补充三点:

您可以在这里找到一篇关于TCP与UDP的非常好的文章 游戏开发的背景。 此外,iperf (jperf增强iperf与GUI)是一个 这是一个很好的工具,可以通过测量来回答你的问题。 我用Python实现了一个基准测试(参见这个SO问题)。在平均10^6次迭代中,UDP发送8字节的差异大约是1-2微秒。

请记住,TCP通常在网络上保存多条消息。如果你想在UDP中实现这一点,如果你想可靠地做到这一点,你将有相当多的工作。你的解决方案要么不太可靠,要么速度较慢,要么工作量巨大。有有效的UDP应用程序,但如果你问这个问题,你的可能不是。

如果你需要在两个还没有通话的IP之间快速发送消息,那么UDP到达的速度至少要快3倍,通常是5倍。

Which protocol performs better (in terms of throughput) - UDP or TCP - really depends on the network characteristics and the network traffic. Robert S. Barnes, for example, points out a scenario where TCP performs better (small-sized writes). Now, consider a scenario in which the network is congested and has both TCP and UDP traffic. Senders in the network that are using TCP, will sense the 'congestion' and cut down on their sending rates. However, UDP doesn't have any congestion avoidance or congestion control mechanisms, and senders using UDP would continue to pump in data at the same rate. Gradually, TCP senders would reduce their sending rates to bare minimum and if UDP senders have enough data to be sent over the network, they would hog up the majority of bandwidth available. So, in such a case, UDP senders will have greater throughput, as they get the bigger pie of the network bandwidth. In fact, this is an active research topic - How to improve TCP throughput in presence of UDP traffic. One way, that I know of, using which TCP applications can improve throughput is by opening multiple TCP connections. That way, even though, each TCP connection's throughput might be limited, the sum total of the throughput of all TCP connections may be greater than the throughput for an application using UDP.

人们说TCP给你的主要东西是可靠性。但事实并非如此。TCP提供给您的最重要的东西是拥塞控制:您可以在DSL链路上运行100个TCP连接,所有的连接都以最大速度运行,并且所有的100个连接都将是高效的,因为它们都“感知”到可用带宽。用100个不同的UDP应用程序尝试一下,所有的应用程序都尽可能快地推送数据包,看看事情对你有多好。

在更大的范围内,这种TCP行为可以防止Internet陷入“拥塞崩溃”。

倾向于将应用程序推向UDP的事情:

Group delivery semantics: it's possible to do reliable delivery to a group of people much more efficiently than TCP's point-to-point acknowledgement. Out-of-order delivery: in lots of applications, as long as you get all the data, you don't care what order it arrives in; you can reduce app-level latency by accepting an out-of-order block. Unfriendliness: on a LAN party, you may not care if your web browser functions nicely as long as you're blitting updates to the network as fast as you possibly can.

但即使你关心性能,你可能也不想使用UDP:

现在,您要考虑的是可靠性,您为实现可靠性所做的许多事情最终可能比TCP已经实现的要慢。 现在您对网络不友好,这可能会在共享环境中引起问题。 最重要的是,防火墙会阻止你。

通过将多个TCP连接“集群化”在一起,可以潜在地克服一些TCP性能和延迟问题;iSCSI这样做是为了绕过局域网上的拥塞控制,但是你也可以这样做来创建一个低延迟的“紧急”消息通道(TCP的“紧急”行为完全被破坏)。