string(Class) has strings attached

29 07 2009

I guess I kinda realized this during my early Matlab days (about a year and a half ago!)… one of the new and most “powerful” features of matlab (we thought) was its ability to dynamically change array sizes and and when more elements were added… eventually of course (thanks to the profiler), we found that this is in fact the MAIN culprit in slow running simulations.

Here’s why

Short answer – The compiler is not God.

Long answer – Well, the compiler is not God. And so, everytime a new element is added, it basically needs to reallocate ALL the data to a new location where it can fit the old array + the one new element. And it does this each time you add one element… 😦

So, what do you do? Stop un-learning good old C and CODE IT WITH A CONSTANT SIZE!

Then came C#. string thinge = “my”; thinge+=” my”;

OMG that is soooo awesome! But again, it does the same thing. We didnt do too many of these things to notice the speed difference, but recently I did. Try doing this in a loop and it takes  ~8000ms for my task… preallocate and it takes ~230ms 🙂 🙂 🙂

Alternatives – use StringBuilder. Its kinda like a linked list, so its cool.

So, next time, think twice before using that += for strings …

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: