Wednesday, December 19, 2012

C# and .NET interview question: -What is short circuiting in C#?




When developers get this .NET interview question many of them get stunned with the name.



Short circuiting occurs when you do logical operations like ‘AND’ and ‘OR’.

 “When we use short circuit operators only necessary evaluation is done rather than full evaluation.
Let me explain the above sentence with a proper example. Consider a simple “AND” condition code as shown below. Please note we have only one “&” operator in the below code.

if(Condition1 & Condition2)
{
}

In the above case “Condition2” will be evaluated even if “Condition1” is “false”. Now if you think logically it does not make sense to evaluate “Condition 2”, if “Condition 1” is false.It’s a AND condition right? , soif the first condition is false it means the complete ANDcondition is false and it makes no sense to evaluate “Condition2”.

There’s where we can use short circuit operator “&&”. For the below code “Condition 2” will be evaluated only when “Condition 1” is true.
if(Condition1 && Condition2)
{
}

The same applies for “OR” operation. For the below code (please note its only single pipe(“|”).)   “Condition2” will be evaluated even if “Condition1” is “true”. If you think logically we do not need to evaluate “Condition2” if “Condition1” is “true”.

if(Condition1 | Condition2)
{
}

So if we change the same to double pipe (“||”) i.e. implement short circuit operators as shown in the below code, “Condition2” will be evaluated only if “Condition1” is “false”.


if(Condition1 || Condition2)
{
}

Taken from the best selling interview question book .NETinterview question by Shivprasadkoirala 

Here’s an awesome video on concurrent generic collections in C#.

Thursday, December 13, 2012

C# and .NET interview question: - What are symmetric and asymmetric algorithms?


Simple but important .NET / c# interview question.

Symmetric and Asymmetric are encryption algorithms. In Symmetric we have one key which encrypts messages and the same key helps to decrypt the message. In Asymmetric there are two keys public key and private key. Public key helps to encrypt message and private keys helps to decrypt the message. Everyone has the public key but the private key is held only by the authorized authority


         

Taken from the best selling interview question book .NET interview question by Shivprasad koirala.























Saturday, December 8, 2012

What is BI Semantic model (BISM) in SQL Server 2012?





Some days back I was installing SQL Server 2012 enterprise service pack 1. During installation when I was running through the setup, it gave me two options (multi-dimensional and tabular) of how I want to install SQL Server analysis service. Below is the image captured while doing installation



At the first glance these options are clearly meant to specify how we want the model design for our analysis service.

Now the first option i.e. “MultiDimensional” was pretty clear as I have been using them right from SQL Server 2005 till today i.e. (Star schema or Snow flake).

After some googling and hunting I came to know about the second option. Let me throw some light on the same and then we will conclude what is BISM.

Now overall we have two kinds of database systems , one is OLTP system where the database design thought process is in terms of tables and normalization rules ( 1st normal form , second normal form and third normal form  database design ) are followed.

The second kinds of systems are OLAP system’s where we mostly design is in terms of fact tables and dimension tables. Cube which is a multi-dimensional view of data is created properly if you design your database as OLAP system.

So in simple words we need to create a DB with OLAP design to ensure that proper cubes structure is created.



Now some times or I will say many times it’s really not feasible to create different structures and then create cubes from them. It would be great if SSAS gives us some options where we can do analysis straight from normalized simple tables.

For instance take simple end users who use “power pivot”. It’s very difficult for them to make understand OLAP models like dimension and fact tables. But yes they do understand tables with rows and columns.  If you see Microsoft excel the format is in terms of tables which have rows and columns and these end users are comfortable with a tabular structure.

 Below is a simple image of how simple end user visualize data in excel i.e. tabular – rows and columns.




That’s where exactly the second option i.e. the “Tabular” mode comes in to picture.

So if we put in simple words BISM (Business intelligence semantic model) is a model which tries to serve simple users / programmers who are comfortable with tabular structure and also maintains professional OLAP models for corporate.



So BISM is a unifying name for both Multi-dimension and tabular models.  So if you are personal BI person who loves ADHOC analysis, you can use power pivot or SSAS tabular IDE to do analysis. And if you are person who is working on a corporate project then Multi-dimension model is more scalable and worth looking in to.



Just a last quick note this is also a favorite SQL Server interview question which is making rounds now a days when SQL Server 2012 topic is discussed.

With all due respect to my publisher I have taken the above answer from my book SQL Server interview questions and answers.

You can also see my blog which has some important for SQL Server interview questions on Colaesce. 

You can also see my video on Can views be updated (SQL Server interview questions) ?



Friday, November 30, 2012

Important SQL Server interview questions on data types: - How many bytes does “char” data type consume as compared to “nchar” data type?


“char” data types consumes 1 byte while “nchar” consumes 2 bytes. The reason is because “char” stores only ASCII characters while “nchar” can store UNICODE contents as well.

In case you are new to ASCII and UNICODE. ASCII accommodates 256 characters i.e.english letters ,punctuations , numbers etc.But if we want to store a Chinese character  or some other language characters then  it was difficult to the same with ASCII  , that’s where UNICODE comes in to picture. An ASCII character needs only 1 byte   to represent a character while UNICODE needs to 2 bytes.

One of my SQL Server friends who had gone for a SQL interview was grilled , whether we can update SQL Server views , I have tried to answer this question here with a video


The above question I have extracted from near to heart book
SQL Server interview questions By Shivprasad koirala by BPB publication

Regards,
Click to view more from authors on SQL Server interview questions and answers



Monday, November 26, 2012

You are 35 and not a manager – The Indian IT society trauma?



I am not trying to underestimate the position of a manager.  But I hate when people point fingers at me and say “You are 35 and still not a manager, till what age can you code?”.
I am so sorry to be harsh, but I really hate those people who for various reasons think that programmers are some kind of useless mass on earth. Do not contradict that many do not think they think and its truth.



By grace of god I am personally at a position where I do not care andI love programming, technology and would like to spend rest of life doing the same. 

But with that statement many good developers would have been converted to bad managers overnight.  Frankly I blame the Indian IT society who thinks after a certain age a person is less capable of  programming.
Leaving my so called personal confidence aside
thought to look at the other side of the mirror on, why majority developers are forced to become managers.









Social trauma
 

For some reasons when someone (especially senior managers) knows you are a developer they start thinking about you as a person who is not a decision maker or probably they  just imagine you as  technical lover  who has  no understanding of how to do business .


Some people also go one step further to conclude that a pure technical person can never be leader or motivate any one.

A person at the age of 30 is considered a failure, if he is involving himself in coding.







A manager allocating resources from a excel sheet is more respected by IT society than a developer or a technical architect slogging to solve problems.

Major people of IT society envy how a manager has his own cabin, how he commands, how he does so called project management, allocates resources, motivates people (some project managers have the illusion that they are bill gates) , implements processes blah blah. This is the first reason I think that a technical person starts thinking that a manager is a better fit than a technical role. He starts dreaming about the comfort zone and luxury enjoyed in a managerial position.

Technical person does not have money or the power
In India the salary difference of a senior technical person and equivalent experience manager is considerable. 

A manager who is working on a excel sheet, PPT and documents are paid more than technical people who actually create the software.

Adding to everything some senior managers have this feeling that a technical person can be made happy by giving challenging technical work and he will not crib for anything. Oh yes, I love technical work but at the end of the day I have to show my face to the family.




I am not saying start paying the senior technical person’s more. But this difference should be minimized so that atleast senior technical people start feeling that yes this role at this is age is also appreciated by the industry.

Technical architect position a joke


Many people can argue that, then choose the path of a technical architect. Oh, gosh, this position in Indian IT industry is abused (sorry for crossing limits) to a extent that there are people who refrain to take this position any more. I sometimes think this position is created to create a illusion that they are growing in their career.

As a technical architect, they expect you do everything. Right from technical solution, to nitty gritty problem solving and providing hands on solution to the developer’s.



Wondering when Indian IT industry will start respecting t
echnical people , give them appropriate respectable position , his words are considered during decision making and he stands shoulder to shoulder with the project manager  in terms of decision making.Sorry for the loud mouth. I do not have the genes to write these kinds of article but I am sure it echoes feelings of lot of technical people out there.Would like to hear from you guys, if your organization has a proper road map for techies and do they really feel comfortable with the road map.


Thursday, November 22, 2012

C# and ASP.NET MVC (Model view controller) interview questions and answers:- What are MVC partial views and how can we call the same in MVC pages?

ASP.NET MVC (Model view controller) partial view is a reusable view (like a user control)which can be embedded inside other view. For example let's say all your pages of your site have a standard structure with left menu,header and footer as shown in the image below.



For every page you would like to reuse the left menu, header and footer controls.So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

When you add a view to your project you need to check the “Create partial view” check box.



Once the partial view is created you can then call the partial view in the main view using "Html.RenderPartial" method as shown in the below code snippet'










Below is an important SQL server interview question and answers video:-




Do visit us for c#  and ASP.NET MVC interview question and answers

See more stuffs on C#/ASP.NET interview questions 

Regards,

Click here to see more C# and ASP.NET interview questions and answers

Thursday, November 8, 2012

SQL Server Interview Question and answers: - How does index affect insert, updates and deletes?

First let me give a short answer so that you can please the interviewer and get your job. If you are inserting heavy data on table which have clustered indexes that will lead to page split. Due to heavy page splits the performance can degrade. So a proper balance of indexes should be maintained for tables which are heavy in transactions and have clustered indexes created.

Now let’s go for a big explanation of what exactly is a page split.

Indexes are organized in B-Tree structure divided in to root nodes, intermediate nodes and leaf nodes. The leaf node of the B-tree actually contains data. The leaf index node is of 8 KB size i.e. 8192 bytes. So if data exceed over 8 KB size it has to create new 8 KB pages to fit in data. This creation of new page for accommodating new data is termed as page split.

Let me explain you page split in more depth. Let’s consider you have a simple table with two fields “Id” and MyData” with data type as “int” and “char(2000)” respectively as shown in the below figure. “Id” column is clustered indexed.

That means each row is of size 2008 bytes (2000 bytes for “MyData” and 8 bytes for “Id”).




So if we have four records the total size will be 8032 bytes (2008 * 4) that leaves 160 bytes free.Do looat the above image for visual representation.

So if one more new record is added there is no place left to accommodate the new record and the index page is forced to go for an index page split.





















So the more we have page splits, the more the performance will be hit as the processor has to make extrefforts to make those page split’s, allocate space etc.

Here’s a awesome video on one more tough SQL Server interview question: -What are CTE (Common table expression) ? , you watch the same from by clicking on



Taken from the best selling SQL Server interview question book, you can see more about the book by clicking on  SQLServer interview questions book Dotnet interview questions and answers book  

See more stuffs on  SQL server interview questions

Regards,

Click here to view more SQL server interview questions and answers .




Thursday, October 11, 2012

.NET Interview questions and answers: -What are different access modifiers?


Taken from my book.NET interview questions http://www.flipkart.com/.
There are 5 access modifiers. Access modifiers define scope for members.

·     Private:  Accessible only with in the class.
·     Protected: - Accessiblewith in the class and in derived classes.
·     Friend (internal in C#):- Accessible anywhere within the current project.
·     Protected friend (protected internal in C#):- Accessible with current project and derived classes.
        ·       Public: - Accessible everywhere.



  

One of interesting .NET interview question: -What is the difference between string and string builder ?










Monday, October 8, 2012

SQL Server SSIS Interview questions: -What is the difference between “For loop container” and “Foreach loop container”?

The “For Loop Container” executes specified number of times like 10 times, 20 times until the specified condition is met.













The “Foreach Loop Container” runs over an iterator. This iterator can be files from a folder, records from ADO, data from a variable etc.






























In case you are fresher to SSIS, SSAS and SSRS you can start seeing our step by step videos from http://www.youtube.com/watch?v=I_Ae3suaL-U

Regards,

Get more C# training stuffs from author's blog





Saturday, September 15, 2012

c# interview question :- What is the difference between Debug and Release?

See the following C# / .NET training video: - In this video we will understand how c# debug and release compile modes are different and when to use them. Debug is mainly meant for development environment while release is meant for production environment.



See for more stuffs on c# interview questions and answers

Regards,

Click to view more from author's on C# training

Friday, June 8, 2012

Site is under maintenance, please visit later: - ASP.NET trick

24 x 7 uptime guaranteed



As a web site owner we all boast about 24 x 7 uptime. But somewhere down below in our hearts we know it’s difficult. We need to bring down the website for maintenance, fixingdefects, upgrading etc.

Easy way…

As an innocent c# ASP.NET developer you would think how about just stopping IIS web server, do your activity(maintenance, fixing defect etc.) and then start the IIS again.



While this looks to be a but obvious way of solving the problem but it’s not the best way if we consider the end user perspective. The end user would see an ugly screen as shown below leading to more confusion.



Rather than end user seeing that kind of absurd screen how about showing something more better and informative like: - “Site is under maintenance and will be live till 3:00 AM”.

Going offline graciously:-App_Offline.htm

Also I would like to highlight here it’s not about showing the error message but technically we would like to ensure that the following things happen in IIS:-
  • Application domain under which the website is running is brought down.
  • All incoming request coming to the ASP.NET site needs to stopped.
  • All request to be routed to the temporary page which is created.
  • After maintenance the application domain should be loaded and the incoming request should be processed in a normal manner.
Thanks to Microsoft they always understand our needs. The proper way of approaching this problem is to create a simple “App_offline.htm” file in your application root directory. In this “App_offline.htm” you can put your user friendly message which the end users can see when the site is under maintenance.
Once done you can delete the file and your web site app domain is loaded and the normal life continues.






You can visit my site for
C# and .NET interview questions and in case you are a fresher you can attend FREE C# training by clicking on C# training videos.

Take a quick look as revision for practical video on "Site is under maintenance"

Monday, June 4, 2012

C# and .NET interview advice for freshers: - Not getting a job for a year should I put fake experience, switch to DBA or pay money for getting a job?

As a .NET interview questions author I always get lots of emails. One of the common things which people ask should I put a fake experience. Below is an answer to one such email.

Sir I've completed b.tech in 2011 ,,,,and searching for a job,,,, I was trained on .NET from NIIT institute ,,,, I've faced some .NET interviews but they are asking for money to pay them,,,,

If someone says pay money to get a job that means they do not need you, you are kind of a baggage on them. Also beware it can be a fraud also. Lately lot of small size software companies and training institutes who are not doing well have turned up to these kind of activities.


When we say we are doing a job, means we are helping company to grow and company pays money in return. So people who are asking for money straight say No No , if that means sitting at home for some time that’s fine, enjoy family.

and other side i am jobless till now and its been 1year,,,and now i don't understand what to do now to see my self as a engineer

If you are jobless for a year you need to see what’s going on wrong. Do connect me personallyfor a mock on .NET interview so that I can personally judge to see what is wrong.

IT market is not so bad. It must be a bit strict for fresher’s but not that horrible as you see. See one is that you are jobless for a year and the other is that in this 1 year you have been to at least 15 interviews and you got till the last round. So if you belong to later part of it that means you are doing well and you should get a job soon.

I personally understand what it means to be at home for a year. But believe me when you get good positions in life ahead you will cherish this struggle and you will be proud of the same.

How about switching to DBA

Courtesy: - http://everydayclimb.files.wordpress.com/

There's a saying in Hindi,DusrokagharSuhanalagtahai( The other side of the grass is always green). .NET, c# has large number of jobs as compared to DBA. Definitely DBA has its own Niche but the numbers of jobs are less. So if for C# you have 100 jobs then for DBA you will have 10. In those 100 c# jobs the number of applicants will be 1000 while in DBA it will be 10.

So one scores high in the number of jobs while the other has less competition. My suggestion would be you have already been trained in NIIT , you are already in full swing of searching a job , stick to .Net for now. You can switch to DBA later when you have a job on hand.

Will a fake 1 year experience help me?


For one Lie you will have to tell 100 Lies ahead. Smaller companies look for people who can code and complete their project. Bigger and mid-level companies look for experience. So start with smaller companies, do not expect sky rocketing salary, be truthful, show your expertise by showing some sample projects. Let them you are serious as well as competent.

I know you will not believe as you are jobless for a year but TRUTH finally wins.

C# interview questions: - What’s the difference between String and String Builder?



Also visit my site for more C# training.

Sunday, May 20, 2012

The unsung hero, Volatile keyword: - c# threading

The unsung hero, Volatile keyword: - c# threading


My mad and blind love with c# threading


When I first saw c# threading code, I just falled in love forever. As days passed by the power and simplicity of “System.Threading” namespace converted my love in to blind love.

Thread t1 = new Thread(SomeThread);
t1.Start(o1);

In case you have not still fallen in love and new to c# threading, you can start looking at my c# training threading video from here.


















The blind love was but obvious because in today’s modern world parallel task execution is compulsory component.My love helped me to please users with mind blowing UI interfaces, multi-threaded batch processes, until one day…..

End of blind love with c# threads
























But one fine day my love with c# thread’s had a bump.I had two threads running and both where updating the same local variable.  The updation done by one thread was not visible to the other thread.

Let me detail what I am saying. I had create a local variable called as “_loop” as shown in the below abstract code snippet. This variable was set to ‘true’ by default.


class Program
{
bool _loop = true;

…        
}

In the same application I had created one function called as “SomeThread” which will run until the “_loop” is true.

private static void SomeThread(object o1)
{
….
….
while (o._loop)
{}
}

From the main thread I was spawning this some thread which was running the loop continuously. In this main thread I was setting the “_loop” to false. In other words the infinite loop of “SomeThread” should stop and exit…VOILA it did not.

static void Main(string[] args)
{
Thread t1 = new Thread(SomeThread);
t1.Start(o1);
o1._loop = false;
….
….
}

Below is the complete source code, you download and see it for yourself. https://skydrive.live.com/redir?resid=658DB05866C4E8A3!257&authkey=!ABOTw_YQ_czfnNc

bool _loop = true;
static void Main(string[] args)
{
            Program o1 = new Program();
            Thread t1 = new Thread(SomeThread);
            t1.Start(o1);
            Thread.Sleep(2000);
            o1._loop = false;
            Console.WriteLine("Value Set to false");
}
        private static void SomeThread(object o1)
        {
            Program o = (Program)o1;
            Console.WriteLine("Loop Starting...");
            while (o._loop)
            {}
            Console.WriteLine("Loop Stopping...");
        }

If you run the above code you can see the infinite loop starting, but I does not end even if the value was set to “false”.


You can also see the actual video demo of the code by clicking on c# training for threading .
Note :- When you run the code ensure that you have selected release  with CNTRL + F5 pressed.


Why did my love ditch me:- Local Thread memory storage and synchronization


After so many years of successful relationship it was difficult to believe this unexpected behavior. So I started googling to get reasons for it.

After long hours of reading, I was stunned that there are two kinds of memory we have to deal when it comes to threading.

One is the main memory where our variables are allocated and the thread also has his own local memory…SURPRISED, same here.

In other words the “_loop” is present at three places one in the main memory and second in the local memories of “mainthread” and “somethread” functions.

When the program kick starts the “_loop” is set to true. So all the memory storages have “_loop” set to true. See the below visual representation.


As the program runs the main thread set the value to false. This updation is done in the local memory of “mainthread” and main the memory, but it does not update the local memory of “SomeThread”. So the “SomeThread” function still sees the stale value and keeps running in a loop.

Below is a visual representation of how things look internally at various points.



The unsung hero: - Volatile keyword
















All relationships have problem, we just need to adjust, find solution and move with life. I was definitely in no mood of leaving c# threading after such a wonderful relationship.

The solution to get around this multiple memory storages was “VOLATILE” keyword.

If you declare your variable as volatile the thread tries to access values from main memory rather than from his local memory where data is stale. It does slow down a bit but it addresses this big confusion.

See it yourself, take the same source code and change the “_loop” variable to volatile as shown in the below code snippet and run it.

class Program
{
  volatile bool _loop = true;

Ensure that you select mode “release” and hit control + f5 to see the expected behavior.








Feel and See it yourself

In case you want to see it live what I have said in this blog see the video below
http://www.youtube.com/watch?v=DZUXDSEuqek

You can also see it yourself by downloading the code from the below link.

I am trainer by profession, interested in c# training , click here c# training .

Friday, May 18, 2012

UML Training: - Elaborate all types of diagrams in UML(Unified Modeling Language)?

There are nine types of diagrams in UML:-

Use case diagram:
They describe "WHAT" of a system rather than "HOW" the system does it. They are used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases". Use Case diagrams shows "actors" and there "roles".

Class diagram:
From the use case diagram, we can now go to detail design of system, for which the primary step is class diagram. The best way to identify classes is to consider all "NOUNS" in use cases as classes, "VERBS" as methods of classes, relation between actors can then be used to define relation between classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship which can easily be identified from use cases.

Object diagram:
An object is an instance of a class. Object diagram captures the state of classes in the system and their relationships or associations at a specific point of time.

State diagram:
A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle. Object change in response to certain simulation so this simulation effect is captured in state diagram. Therefore, it has a initial state and final state and events that happen in between them. Whenever you think that some simulations are complicated, you can go for this diagram.

Sequence diagram:
Sequence diagrams can be used to explore the logic of a complex operation, function, or procedure. They are called sequence diagrams because sequential nature is shown via ordering of messages. First message starts at the top and the last message ends at bottom. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step by step. Different objects in the sequence diagram interact with each other by passing "messages".

Collaboration diagram:
A collaboration diagram groups together the interactions between different objects to fulfill a common purpose.

Activity diagram:
Activity diagram is typically used for business process modeling, for modeling the logic captured by a single use case, or for visualizing the detailed logic of a business rule. Complicated process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions. However, difference is state diagrams are in context of simulation while activity gives detail view of business logic.

Deployment diagram:
Deployment diagrams show the hardware for your system, the software that is installed on that hardware, and the middleware used to connect the disparate machines to one another. It shows how the hardware and software work together to run a system. In one, line its shows the deployment view of the system.

Component diagram:
The component diagram represents the high-level parts that make up the system. From .NET angle point of view, they form the "NAMESPACES". This diagram depicts, at a high level, what components form part of the system, and how they are interrelated. Its shows the logical grouping of classes or group of other components.

See the following video on UML diagram: -



Click to get UML Training

Regards,

Get more UML training stuffs from author's blog

Tuesday, May 15, 2012

C# Training: - Elaborate various types of IIS isolation levels?

IIS has three level of isolation:-

LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects everyone.

Figure: - LOW IIS process scenario

Medium (Pooled):-
In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running.

Figure: - Medium pooled scenario

High (Isolated):-
In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.

Figure: - High isolation scenario

See the following video on ASP.NET4.0 Redirectpermanent: -



Click to get C# Training

Regards,

Get more C# training stuffs from author's blog

Thursday, May 3, 2012

ASP.Net Interview questions: - Mention differences between ‘Server.Transfer’ and ‘response.Redirect’?

Following are the major differences between them:-

‘Response. Redirect’ sends message to the browser saying it to move to some different page, while server. Transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in ‘server. Transfer’ there is no round trip while ‘response. Redirect’ has a round trip and hence puts a load on server.

Using ‘Server. Transfer’ you cannot redirect to a different from the server itself. Example if your server is www.yahoo.com you cannot use server. Transfer to move to www.microsoft.com but yes, you can move to www.yahoo.com/travels, i.e. with in websites. Cross server redirect is possible only by using Response. Redirect.

With ‘server. Transfer’ you can preserve your information. It has a parameter called as “preserveForm”.Therefore, the existing query string etc. will be able in the calling page.

If you are navigating within the same website use “Server. Transfer” or else go for “response.Redirect ()”

See the following video on ASP.NET4.0: -



Click for more ASP.NET interview questions

Regards,

Visit for more Authors’ blog on ASP.NET interview questions

Wednesday, May 2, 2012

Strings are from earth and StringBuilder from mars.

Introduction


I was happily married to string for a long time until I came to know the reality that “Strings are immutable” and not suitable for all scenarios. Recently I was working on a heavy HTML parser application and the program used to go out of memory frequently. The completely HTML parsing logic was using string variables.

After reading around I came to know the main reason was the immutable behavior of string. Immutable means once the data is assigned cannot be changed.

For instance if you are looping using a string variable like the code given below. Every assignment to the string creates new copies of variables and the previous copy is sent for garbage collection. So the below for loop generates different memory copies of data and the recently created is the current value.

   

Now you must be wondering why this absurd behavior. Any lame person (like me) can conclude this is not efficient and neither looks logical.

The sacrifice for thread safety


Before I start with the solution I wanted to understand why Microsoft team thought about this weird behavior. Thanks to http://stackoverflow.com/questions/2365272/why-net-string-is-immutable things started looking logical.

If you are using string variables in multithreaded scenarios every thread modification will create new copy of memory ensuring that you do not land in to multi-threaded issues. In other words thread safety is built-in by itself when new copies of data are created.

Not all work on ships


The next thing which started itching me is what if my application is not multi-threaded. What if my main motive is to save memory resources and ensure that I do not go out of memory issues?. Here’s comes the hero from mars “StringBuilder”.

“Stringbuilder” are not immutable, in other words if you change the variable data the same memory location is modified. VOW, that looks lot of memory saving during heavy concatenation operation as compared to string.

 

I wanted to see for myself that earth is flat


As a curios developer it was difficult for me to digest that internally string creates different copies of data. Out of curiosity I downloaded the CLR Profiler and ran two test of code as shown below.

One for string as the below.

string x ="";

for (inti = 0; i< 10000; i++)
{
x = "Shiv"+ x;

}


 

One for string builder.

StringBuilder x = newStringBuilder();

for (inti = 0; i< 10000; i++)
{
x.Append("Shiv");

}



Watch the allocated bytes, 400235631 bytes is way greaterthan 136597bytes.

Watch the video below for the real demo


If you do not believe what I have written see the actual video demo as follows