Archive for May 2008
Convert IList to List<T>
Follow up with my NHibernate Series today I have another post talking about one of my favorite Util’s method.
This come from my heavy use of NHibernate classes such as DetachedCriteria, IMultiCriteria and I love to call on it .SetResultTransformer method to transform result into strong type; however its .List() method return an IList which doesn’t uncomforted me much because I addicted to generic & strong type object.
public static IList<T> ConvertToListOf<T>(IList iList)
{
IList<T> result = new List<T>();
foreach (T value in iList)
result.Add(value);
return result;
}
With this little method it allow me to work with generic type again and that is sweet ;)
EDIT: hmm, I just discovered something interesting actually I don’t really need this at all I can just manipulate iList element through foreach().
namespace ConsoleApplication1
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
internal class Program
{
private static void Main(string[] args)
{
IList x = new ArrayList();
for(int i = 0; i < 100000; i++)
{
x.Add(new Person("First #" + i, "Last #" + i));
}
Stopwatch watch1 = new Stopwatch();
watch1.Start();
foreach(Person person in x)
{
Console.Write(person.FirstName);
Console.Write(person.LastName);
}
watch1.Stop();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
IList<Person> persons = ConvertToListOf<Person>(x);
foreach(Person person in persons)
{
Console.Write(person.FirstName);
Console.Write(person.LastName);
}
watch2.Stop();
Console.Clear();
Console.WriteLine("Watch #1: {0}\r\nWatch #2: {1}", watch1.Elapsed, watch2.Elapsed);
Console.Read();
}
public static IList<T> ConvertToListOf<T>(IList iList)
{
IList<T> result = new List<T>();
foreach(T value in iList)
{
result.Add(value);
}
return result;
}
}
public class Person
{
public string FirstName;
public string LastName;
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
However it come down to an interesting measurement issue
* Pass through *
Watch #1: 00:00:00.0075761
Watch #2: 00:00:00.0131754
* Pass through & read field *
Watch #1: 00:00:06.2585406 (process direct)
Watch #2: 00:00:06.3542894 (convert first)
PHP Suck ?!
It came as a surprise to read half of Jeff Atwood’s post title, PHP Sucks, But It Doesn’t Matter. But I truth this guy he always had a reason to write about these thing and I am totally agreed when he says:
Building a compelling application is far more important than choice of language.
Sufficiently talented coders can write great applications in terrible languages, too.
It’s a painful lesson, but an important one.
