站内搜索: 请输入搜索关键词
当前页面: 图书首页 > NET For Java Developers Migrating To C#

NET For Java Developers Migrating To C#

[ directory ] Previous Section Next Section

2.3 C# Performance

Java programmers know about Java's performance issues, so at this point it is only fair to quickly glance at C#'s performance.

A good test of a language's performance is to see how long it takes the two languages to iterate over a for loop 10 million times. Listing 2.13 shows the C# code, and Listing 2.14 shows the corresponding Java code. Note that in C# Environment.TickCount returns the time elapsed in milliseconds since the system started. This is a close equivalent of Java's System .currentTimeMillis() function.

Listing 2.13 Iterating 10 Million Times (C#)
1     using System;
2     public class ForLoopTest {
3       public static void Main(string[] args) {
4           long start = Environment.TickCount;
5           for (int i =0;i < 10000000; ++i) {
6           }
7            long end = Environment.TickCount;
8            Console.WriteLine((end-start));
9           }
10    }
Listing 2.14 Iterating 10 Million Times (Java)
1     public class Performance {
2     public static void main(String[] args) {
3          long start = System.currentTimeMillis();
4          for (int i=0; i < 10000000; ++i) {}
5          long end = System.currentTimeMillis();
6            System.out.println(end-start);
7     }
8     }

The C# console prints 50, and the Java console prints 120. With this simple test we cannot conclude that the C# runtime is faster than the Java runtime; these results depend on several factors, such as hardware and software configuration. Java programmers might be curious to see such kinds of performance tests, but it is beyond the scope of the book to jump into performance testing.

    [ directory ] Previous Section Next Section