2.06.2007

C# Objects - Does it create a new one?

In response to whether a new object is created during a particular type of loop, I gave the following answer. It has to do with what type of variable you are using, but sometimes the CLR creates a new object when you wouldn't expect it. Strings are one well-known cause of this, but it's important to understand the reasons why. The string is a special case because of the way C# implements it as an object, not because of some factor of the C# language or the compiler itself - it's an implementation detail, not a language feature. Most object references will not result in a new instance of the object simply from changing its value. For string though...

string s = "myString";
s = "another value";

That results in two instances of the string being created (and the one that says "myString" is now "lost" and will be garbage-collected). This is because strings are implemented as immutable objects, meaning their value can never be changed. In order to allow for normal programming constructs, the CLR simply creates a new string whenever the value is changed, discards the old string and assigns the new string to the reference. There are historical reasons for choosing this implementation, security being one of them (notably, the buffer overrun exploit). The .Net Framework provides the StringBuilder class to overcome performance limitations with strings of this type. For most other types of objects, that doesn't happen. If it's an int, you only get one instance, no materr how often you change the value.

int i = 25;
i++;
i = i+ 20;
for (i = 0;i < 20; i++) {
 //do some stuff
}

That whole block only results in one instance of i, since you're only changing the value. This:

for (int i = 0; i < 20; i++ {
 //do some stuff
}

This also results in only one instance of i. This on the other hand:

for (int i = 0; i < 20; i++) {
 int k = 10;
 //do some stuff with k
}

That will result in 20 instances of k, all of which will be garbage-collectable at the end of the loop. The type doesn't matter there. If you did this with a reference type, a string, whatever... you will get 20 instances of the thing, and they will all be thrown to the garbage collector, unless you pass them as a reference to some other thing. In some cases... this is what you want. Like this:

for (int i = 0; i < 20; i++) {
  ListItem li = new ListItem();
  //add the li to a ListView
  listView1.Items.Add(li);
}

That creates 20 instances of a ListView object (maybe 40, see below), but they will not be garbage-collected after the loop because someone else (the ListView) is holding a reference to those 20 new things. The fact that I called it 'li' each time is of no consequence, I can recycle the variable name as much as I want. Now, here's where it gets confusing. If I did this the other way...

ListItem li = new ListItem();
for (int i = 0; i < 20; i++) {
  //set some values for li and add it to the view
  listView1.Items.Add(li);
}

This will not create 20 instances of li, there will only be one and I can change its values around all I want. So... am I adding the same object to the ListView 20 times, or is the ListView making a copy of the object 20 times, resulting in 21 ListItem objects total? I know it will result in the ListView showing 20 things and they can all have different values... so I think it's generating a copy with the Add() method. I am pretty sure of that, but I'm asking if anyone knows for sure.

My overall point is that you can't use the rule "ref type, one behavior, value type, other behavior", because the situation is more complicated than that. You can see there are some obvious cases where you get a new instance, but there's some other, less obvious cases (such as string), where you get new instances because of some implementation detail of the objects involved. With string, I get a new instance because string is implemented to create a new one when the value is changed, with my ListItem, I'm getting a new instance because of the implementation of the ListItemCollection which I'm adding it to. Am I right about this?

The person who asked this question was asking what is "best" in their case, but it's pretty hard to figure out what is best, and it won't be best in all cases. However, if you know how things operate at a lower level, you can decide what's best with much more confidence. BTW, this is one thing I don't like about .Net (not C# really, I think .Net is the Evildoer here)... I'm not always clear about the performance costs of particular methods, since the .Net Framework likes to create new object instances willy-nilly like memory has no limits.

Clear as mud?
Jasmine :)

1.25.2007

Freeware Link Checker and Google Sitemap Tool

I created a freeware tool that I use to check for broken links on my sites. It works quite nicely! It does the same things that Inspyder's tool does, but for free. I know there are many tools like this out there, but I ask you to try this one and let me know how you like it!

Go here to download:

Jazzy's Web Widgets

Thanks very much!
Jasmine

1.14.2007

Killed a bug today...

It was a Box Elder Beetle (left), which is not actually a beetle (order Coleoptera) at all, but is truly a bug (order Hemiptera). I'm not here to discuss taxonomy - I'm writing today to discuss the killing of insects, spiders and other creepy-crawlies and why I think a man, if available, should carry out this task. I think men should really stop giving us so much crap about this - just do it.

Normally I'm not the type of person who kills a bug, or spider or whatever. I usually let them roam around my house at will, but I wasn't really sure why. I tried to rationalise it by saying things like "well, they don't eat much", or "it's probably here eating worse things I'd rather not know about." Since I have a degree in Biology, I can identify most types of spiders and insects commonly found in homes and I usually have some idea of what kinds of activities they might be carrying out in my domain. Most of the time, I consider them responsible citizens of my little slice of the world, but occasionally a critter will push it's luck and Jazzy has to give it the smack-down.

If you've ever watched a woman perform this activity you know it can be quite comical, involving copious amounts of toilet paper, a slow stealthy approach, and a lightning-quick strike. This is usually followed by repeated confirmation that the thing is not going to strike back, and discarding of the victim in the toilet. I usually watch to make sure it goes down too. Many people have observed this phenomenon and assume that women are afraid of bugs.

I say no, we are not any more afraid of bugs than anyone else... we just don't want to be connected with the act of killing. I know this is true because I'm not afraid of bugs. I'm not afraid to touch them at times when I'm not about to end their life. I've handled many insects and spiders in my life, but I don't like them in my house... at least not if they are going to be brazen enough to crawl right in front of me.

Today when I killed this poor soul, I experienced an unusually lucid emotional moment. I was genuinely sorry that I had to kill this creature, and would have rather had it any other way. I briefly thought about taking it outside, but it's 18(F) degrees outside and that would surely kill it as well. As I watched it crawl across my bathroom mirror (I know, creepy), I actually took a few moments to consider possibilities for saving it's life. I wished with all my heart that someone else could do this for me. Then I reluctantly performed the standard bug-elimination procedure detailed above. I suddenly realized, women aren't afraid of bugs at all, we are afraid of killing. I don't want to be involved with that kind of carnage. It actually put me in a bad enough mood that I had to blog about it. I also realized that the standard bug-elimination procedure is merely an attempt to disconnect myself from the act of killing. As in, "if I don't really touch it, then it wasn't me who killed it."

All this destruction is better kept out of sight, and if there was a man around I would have begged him to carry out this activity on my behalf, in order to disconnect myself even more. I would still feel a little bad about contracting a hit man, but conspiracy to kill insects is a little less serious in my mind. So men, please, no more crap about us being afraid of a little bug, just be our hit-men and do it. I (meaning you) will be much happier without the emotional baggage of being a murderer following me around the rest of the day.

12.11.2006

Be a programmer, but not today

This author is pretty much correct, but I have to expand on it a bit. You can't become a good developer in 21 days, although if you are already experienced, you can learn a new language pretty fast. Probably you can't become a good developer in less than 5 years, and that's if you have a natural aptitude for it. Ten years of plugging away at something doesn't make you an expert either. I've played guitar for 20 years and I pretty much still suck at it, but I enjoy it and I am 100x better than I was after my first week of playing. The one thing I think this author and everyone who addresses this question, is missing is the suggestion that learning programming languages means anything at all. If you want to be a good developer, focusing on languages is not the way to go. Everything else I agree with but I would phrase it a different way:

1. Make sure you enjoy it. Good programmers really love coding. They are known for staying up for days on end to write code, because they are so excited about it that they can't sleep. BTW, it's not the coding that keeps me up at night, it's the pursuit of better ways to solve a problem. Very important: be a connoisseur of problem-solving, and methods of attack. A good programmer is just as likely to stay up all night solving a crossword as they are to be coding.

2. Talk. Be social. One thing that I wish would come back into vogue is the development-based user group. I'm talkin about local groups that get together in person. Online forums are great but no substitute for crowding around a screen and actually learning something in a group. Know programmers, meet them in person, have drinks. Get out in the real world and interact. Programmers are known for being an antisocial bunch, but the best programmers love to get together and share.

3. Practice, a lot. Start by building the hello world example to get a feel for whatever you're learning, but then go ahead and dive into something complex. Figure it out along the way, by using #1 and #2. When I learned C++, the first thing I made (after hello world) was a linear algebra class library. One of the first BASIC programs I ever completed was a version of Othello for the Vic-20. Do something like that... if you can't hack it, better that you learn that early. Getting bogged down with things you don't understand isn't the way to go, but learn concepts slowly and build them up into a complex program.

4. Get a degree... if you want to work as a programmer. Having a degree will help open up more opportunities... it's like Boot Camp for higher-level jobs. Your degree does not have to be in Computer Science, just have a degree in something. My degree is in Biology, with minors in CS and Math... this helps tremendously.

5. Debug - a lot. Debug your own code, upgrade your own code after a few years of ignoring it. Read lots of sample code and try to hack sample projects you find. Debug someone else's mistake. Answer questions on forums. Accidentally break something and then fix it. Knowing what can go wrong is half the battle of preventing it. Being able to handle the unexpected is the other half.

6. Know how computers work. You should have knowledge of what it means to write a computer instruction, and what will happen at the electronic level when your code is executed. Know how processors execute instructions, and know how data is transferred around to various parts of the system. Know the parts of the system, and be able to compare their differences and know about their similarities. A hard drive has a bunch of chips in it... what are they doing, and how are they different from the cpu or the gpu or the math co-processor chips? Those are the questions you should have knowledge of... not expert knowledge, but basic knowledge of how it works.

7. Learn 2 programming languages - SQL and something else. SQL is the most commonly used declarative language, and you will need to know it for most jobs. Don't just learn the language either, learn how to use it effectively and learn it along side another language so you can compare the declarative and procedural styles and learn which to use where. Your 'something-else' language will more than likely be obsolete by the time you become an expert in anything, so struggling to learn multiple languages is a waste of time. Learn what you need to be functional now, and focus on other languages when you have time. (So, learn SQL and C#, VB or Java)

8. Without focusing on multiple languages, learn the concepts that are common to all languages. The list from the article (class abstraction (OOP), functional abstraction, syntactic abstraction, declarative specification, co-routines, paralellism) can all be learned within the framework of C# and SQL. There is no reason to learn Lisp simply to understand syntax abstraction, since almost every language supports that feature to some extent. Lisp takes it to the extreme, and IMO, is not a well-balanced language for a beginner.

I disagree about learning an interactive language (although SQL can be good in that respect). I think a developer should get used to the 'code-compile-test-debug' cycle early on. My intern is struggling right now because he doesn't compile often enough... so when he finally does, he has introduced lots of errors, which sometimes compound each other. Learn the consequences of that behavior right up front.

When you are an expert, you will be able to learn a new language in 21 days, maybe less, so the book titles are misleading by making you think they are targeted to 'fast-track' beginners. If you've ever read one of those books, you would see what I mean... it basically starts by saying you need to know the basic concepts of programming as a prerequisite for understanding the book (usually). I learned C# in a few days, but I had years of experience with the concepts first. The "dummies" books are for beginners, and if you take a look at the Java for Dummies book and the Java in 21 days book (both of which I own), you can see that difference. One is focused on learning both the concepts and the language, while the other is focused on quickly learning the language, but assumes you understand the basics already.

So yeah, teach yourself a language in 21 days if you want to, but if you want to be a good developer, you're going to do a lot more than just learn a language or two.

Good luck!
Jasmine

 
hit counter script