问题描述
我分析了一些样板 UDP 代码,速度非常好,只发送少量数据(这是我的意图).
I profiled some boilerplate UDP code and the speed was very good for sending only some small amount data (which is my intent).
但是与发送"方法相比,连接"方法非常慢".这需要 50 - 80 毫秒:udpClient = new UdpClient();
udpClient.Connect("HOSTNAME", 11000);
BUT the "connect" method is "very slow" compared to the "send" method.
This takes 50 - 80 ms:
udpClient = new UdpClient();
udpClient.Connect("HOSTNAME", 11000);
发送几乎不会以 1 毫秒为单位进行分析,因为它的速度非常快:Byte[] sendBytes = Encoding.ASCII.GetBytes("有人在吗?");
Sending is then hardly profiled by 1 ms, because its so amazing fast:
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length);
我想知道这个连接"方法有什么作用,因为 UDP 在设计上是无连接的.
I wonder what this "connect" method does, since UDP is connectionless by design.
如果我省略了连接方法,那么每次调用的发送速度会变慢:udpClient.Send(sendBytes, sendBytes.Length,"HOSTNAME",1100);
If I leave out the connect method, then send is slower per call:
udpClient.Send(sendBytes, sendBytes.Length,"HOSTNAME",1100);
有没有提高连接"速度的机会?
Any chance to improve the "connect" speed?
免责声明:我知道 UDP 是不可靠的,但对于我的应用程序(客户端统计数据,无论如何都不是 100% 准确),如果包裹顺序错误,甚至一些丢失的包裹也不会杀死我,这并不重要.
Disclaimer: I know UDP is unreliable, but for my app (client statistics, which are not 100% exact anyway) it doesn't matter if packages come in wrong order and even some lost packages don't kill me.
推荐答案
udpClient.Connect 设置默认的主机名和端口,因此您可以在不指定它们的情况下调用Send.需要时间的是名称解析 - 将 HOSTNAME 转换为 IPAddress.
udpClient.Connect sets the default host name and port, so subsequently you can call Send without specifying them. What's taking the time is the name resolution - translating HOSTNAME into an IPAddress.
如果您在 Connect 中执行一次,则不必每次发送时都执行此操作,这样更快.
If you do it once in Connect, you don't have to do it every time you Send, which is faster.
这篇关于UDP“连接"-C#中的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!