views:

38

answers:

3

E.G. I was reading some source code recently.

and someone had the code.

array = "name1 name2 name3 name4 name5".split()

Which is really fast/easy to write. While if I had written the code I would've went.

array[0] = name1    
array[1] = name2    
etc...

Which takes way longer!

So I was wondering where I could find some writing efficiency tips. Or you can post some if you can think of them.

I program mostly in python and C

edit1: I make programs for personal use so runtime isn't that huge of an issue unless it hurts the useability.

edit2: So coding time is more important than a 10% faster runtime.

edit3: @kevin shorter, not cryptic one liners but things like your suggestion, (thanks)

A: 

Well, clearly skipping parsing is faster at run time, since it will be done each time you run the script. But, using a string may make it easier to type the code, and pay a small performance penalty at run time.

Michael Goldshteyn
+1  A: 

The first way, you are adding the overhead of the call to split(), every time your code executes (which you would probably never notice). If this is python, you could just do array = ["name1", "name2", "name3"] which would save you some typing and does not rely on a function call.

As for coding "efficiency" tips, are you looking for ways to write shorter code? Or to write more optimized code?

Kevin
+1  A: 

You should write always code with the intention of making it as readable as possible. Take the following example:

array = "one four ninety-one one-hundred-and-six three-thousand".split()

vs

array[0] = "one";
array[1] = "four";
array[2] = "ninety-one";
array[3] = "one-hundred-and-six";
array[4] = "three-thousand";

I know which piece of code I would prefer to find.

In addition to this the top snippet requires extra processing of the string on each execution.

irishbuzz