<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1837</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1837" rel="self"/>
  <title>xeon06.myopenid.com</title>
  <updated>Mon Dec 07 20:59:43 -0800 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1122</id>
    <published>2009-12-07T20:59:43-08:00</published>
    <updated>2010-01-19T18:40:42-08:00</updated>
    <title>[C#] Line splitting optimization</title>
    <content type="html">&lt;p&gt;This is a console logging function. I'm trying to get the lines to split if they don't fit the display (checked with MessageFits, included). However, the code takes a good second to execute with a message of 1000 characters or more. Is there any way this could be faster?&lt;/p&gt;

&lt;pre&gt;private static void Log(object message, MessageType type)
		{
			string str = message.ToString();

			//Handle newlines
			if (str.IndexOf('\n') &amp;gt;= 0)
			{
				foreach (string s in str.Split('\n'))
					Log(s, type);
				return;
			}

			
			//Split the string recursively in smaller strings to fit the console window
			for (int i = str.Length; i &amp;gt; 0; i--) //TODO: Optimize, adding a message of 1000 characters takes too long
			{
				if (MessageFits(str.Substring(0, i)))
				{
					messages.Add(new Message(str.Substring(0, i), type));

					//If user was already all scrolled down, keep him scrolled down
					if (shownMessage == messages.Count - 2)
						shownMessage = messages.Count - 1;

					Log(str.Substring(i), type); //Recursive call to handle the rest

					break;
				}
			}

		}

		private static bool MessageFits(string message)
		{
			return font.MeasureString(message).X &amp;lt;= window.ClientBounds.Width - (padding * 2) - scrollBarWidth;
		}&lt;/pre&gt;</content>
    <author>
      <name>xeon06.myopenid.com</name>
      <email>no-email@refactormycode.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1122-line-splitting-optimization" rel="alternate"/>
  </entry>
</feed>

