L
Lalit Pant
I'm a newcomer to Ruby, and thought I would write a little
brute-force-search program to see how Ruby compares to Java -
performance wise. The results surprised me (I was hoping Ruby would
fare a lot better than it did!). On my WinXP box (AthlonXP 1800+,
768Meg RAM), the Ruby program takes 1min 50secs to complete, while a
similar java program takes 0.6 secs.
Here are the programs:
Ruby (ruby 1.8.0 (2003-08-04) [i386-mswin32]):
def isPrime(n)
for i in 1..n-1 do
for j in 1..n-1 do
if i * j == n then
return false
end
end
end
return true
end
puts isPrime(2)
puts isPrime(4)
puts isPrime(7)
puts isPrime(25)
puts isPrime(400003)
Java (HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)):
public class Prime
{
public static void main(String[] args)
{
Prime p = new Prime();
System.out.println(p.isPrime(2));
System.out.println(p.isPrime(4));
System.out.println(p.isPrime(7));
System.out.println(p.isPrime(25));
System.out.println(p.isPrime(400003));
}
private boolean isPrime(int n)
{
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if (i*j == n)
{
return false;
}
}
}
return true;
}
}
Kindly note that the isPrime() method above is not meant to be the
most efficient way of finding primes!
Any ideas on why i'm seeing such a big difference in performance?
brute-force-search program to see how Ruby compares to Java -
performance wise. The results surprised me (I was hoping Ruby would
fare a lot better than it did!). On my WinXP box (AthlonXP 1800+,
768Meg RAM), the Ruby program takes 1min 50secs to complete, while a
similar java program takes 0.6 secs.
Here are the programs:
Ruby (ruby 1.8.0 (2003-08-04) [i386-mswin32]):
def isPrime(n)
for i in 1..n-1 do
for j in 1..n-1 do
if i * j == n then
return false
end
end
end
return true
end
puts isPrime(2)
puts isPrime(4)
puts isPrime(7)
puts isPrime(25)
puts isPrime(400003)
Java (HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)):
public class Prime
{
public static void main(String[] args)
{
Prime p = new Prime();
System.out.println(p.isPrime(2));
System.out.println(p.isPrime(4));
System.out.println(p.isPrime(7));
System.out.println(p.isPrime(25));
System.out.println(p.isPrime(400003));
}
private boolean isPrime(int n)
{
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if (i*j == n)
{
return false;
}
}
}
return true;
}
}
Kindly note that the isPrime() method above is not meant to be the
most efficient way of finding primes!
Any ideas on why i'm seeing such a big difference in performance?