\$\begingroup\$
\$\endgroup\$
4
As you can see here:
20% CPU in a 3 minutes and 20 seconds excessive 40 executions async/await at a time for 9700 times caused quite a bit of CPU usage.
Code:
public MemoryStream getMessageBody()
{
#region Get MessageBody
IEnumerable<BytesWraper> MessageBody = GetMessageBodySource();
if (MessageBody == null) {
return null;
}
#endregion
#region Write MessageBody's Data to a MemoryStream so we can convert it later to a String
MemoryStream memoryStream = new MemoryStream(ContentLength == -1 ? 0 : ContentLength);
try {
foreach (BytesWraper bytes in MessageBody) {
memoryStream.Write(bytes.Value, 0, bytes.Length);
}
} catch (Exception) {
return null;
}
#endregion
if (ConnectionClosed()) {
_request.Dispose();
}
MessageBodyLoaded = true;
return memoryStream;
}
Is there a way here to reduce the amount of usage by this foreach call? Perhaps not need to do it at all?
All im then doing with the result is as follows:
return MessageBody != null ? CharacterSet.GetString(MessageBody.GetBuffer(), 0, (int)MessageBody.Length) : null
(where MessageBody is getMessageBody())
t3chb0t
44.6k9 gold badges84 silver badges190 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
Have you tried something like this (?):
MemoryStream memoryStream = new MemoryStream(MessageBody.SelectMany(mb => mb.Value).ToArray());
answered May 3, 2018 at 12:25
user73941user73941
-
1\$\begingroup\$ Edit: So I actually went with your one as it actually essentially did the same as mine, and if there was any performance impact then it wouldnt have been much like at all. Just edit it to the following:
Encoding.UTF8.GetString(MessageBody.SelectMany(mb => mb.Value).ToArray());
as this returns as a string which is essentially what I was wanting. \$\endgroup\$Ma Dude– Ma Dude2018年05月03日 12:38:45 +00:00Commented May 3, 2018 at 12:38 -
\$\begingroup\$ @ImPRAGMA mhmm... but the
foreach
should be faster here anyway so it's not necessarily an improvement if your goal is better performance. Did you measure it? \$\endgroup\$t3chb0t– t3chb0t2018年05月03日 12:54:34 +00:00Commented May 3, 2018 at 12:54
lang-cs
BytesWrapper
is and what you are actually doing here? Saying this code is slow, need help isn't very clear. Help us help you and explain what you're doing in more detail. \$\endgroup\$