[H-GEN] Which is better?

Andrae Muys andrae at internode.on.net
Sun Apr 25 05:58:03 EDT 2004


Harry Phillips wrote:
> A bit of background: I started Uni this year and am doing COMP1500, it's a
> course teaching Object oriented programing using Java.
> 
> I have a question about coding technique. I will give two examples and
> would like to know if anyone knows which is more effcient or if they are
> the same.
> 

What is it about first-years and performance?  They seem to come with 
this stupid fixation built-in; I know I did.  Let me make myself clear 
from the start:

You do not need to know.

You do not want to know.

If you knew enough to understand the answer, you would know the answer.

So I'm not going to try.  However in a couple of years, I have no doubt 
you will be more than capable of telling me the answer yourself.

In the meantime, I suggest you remember that code is read 10x more often 
than it is written.  So my question to you is: "Which is easier to read".


int[] nums = new int[len];
int i;
...more code.
for (i = 0; i < len; i++) {
   nums[i] = i;
}

or

int[] nums = new int[len];
int i;
...more code.
for (i = 0; i < nums.length; i++) {
   nums[i] = i;
}

or

nums = range(0, len)

or

nums = [0..len]

And once we begin operating on the sequence:

int[] squares = new int[len];
...more code
for (i = 0; i < len; i++) {
   squares[i] = nums[i] * nums[i];
}

or

int[] squares = new int[nums.length];
...more code
assert squares.length == nums.length;
for (i = 0; i < nums.length; i++) {
   squares[i] = nums[i] * nums[i];
}

or

squares = [i * i for i in nums]

or

let square x = x * x in
   squares = map square nums

Andrae Muys

(btw.  The third and fourth examples in each case are python and haskell 
respectively)

P.S:  Can you describe to me how the above might be done in an Object 
Oriented way?

P.P.S:  Given that the above code snippets aren't written in an OO 
style, what style are they written in?





More information about the General mailing list