[Best Practice #2] Specify length of collections when you know it.

In the past of programming, developers were fighting for every single byte of memory and every single computing cycle. But with advancement of computers, with memory getting more and more cheaper, with programming languages getting more user friendly and offering compiler sugar, developers got lazier. But this is a good thing. Software gets insanely complex, which requires powerful computers and high level programming languages, that provide many things out-of-the-box.

Unfortunately times change. Today we live in the cloud. We need to design our software so it can withstand massive loads of traffic and parallel execution. This paradigm kinda brings back the old days. It starts to really matter what we do under the hood. Each line is again important. Each object reference is crucial.

In that direction, today I want to talk about the useful collection classes like List<T> and Queue<T> that the .NET Framework provides for us. Out of the box many times developers overuse those classes without thinking of the consequences. One particular feature I want to stress in this article is the two different constructors that those classes have. I will focus on List<T>.

The class has three constructors, but I will talk about two of them.

Do you remember the time before List<T> was available? How do we represent collections of the same item in programming? We use arrays, of course. And there comes this magical class that gives us a collection that you can easily Add and Remove items to. Because as you know, arrays, once declared, have a fixed number of elements. If you wanted to add elements to the collection, you needed to create a new array with bigger capacity and copy all of the old elements to the new array.

Well, as it comes to no surprise, this is exactly what List<T> is doing. A quick look at the class source code, we can see  that there is a private member:

private T[] _items;

So what happens when we create a List<T> with no capacity? An empty array is being created and from that point, every time we add an element, the code sets new capacity to the array by creating a bigger one and coping the elements to the new one.

On the other hand if we set the capacity beforehand in the constructor, then all of the adding of elements just populates elements of the already allocated array.

You can imagine how this can impact performance and memory consumption.

To demonstrate the difference I have created a small test using the awesome BenchmarkDotNet library.

using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;

namespace Blog.BestPractices
{
    class Program
    {
		static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<TestLists>();

            Console.ReadLine();
        }
    }

    [MemoryDiagnoser]
    public class TestLists
    {
        private const int _iterations = 1000000;

		[Benchmark]
        public void TestNormalList()
        {
            var list = new List<byte>();
            for (var i = 0; i < _iterations; i++)
            {
                list.Add(123);
            }
        }

        [Benchmark]
        public void TestScopedList()
        {
            var listWithLength = new List<byte>(_iterations);
           
            for (var i = 0; i < _iterations; i++)
            {
                listWithLength.Add(123);
            }
        }
    }
}

And here are the results of that benchmark:

// * Summary *

BenchmarkDotNet=v0.10.9, OS=Mac OS X 10.12
Processor=Intel Core i5-4250U CPU 1.30GHz (Haswell), ProcessorCount=4
.NET Core SDK=1.0.4
  [Host]     : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT
  DefaultJob : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT


         Method |     Mean |     Error |    StdDev |    Gen 0 |    Gen 1 |    Gen 2 |  Allocated |
--------------- |---------:|----------:|----------:|---------:|---------:|---------:|-----------:|
 TestNormalList | 6.349 ms | 0.0941 ms | 0.0880 ms | 492.1875 | 492.1875 | 492.1875 | 2048.48 KB |
 TestScopedList | 5.279 ms | 0.0636 ms | 0.0595 ms | 242.1875 | 242.1875 | 242.1875 |  976.63 KB |

You can see that using the list with fixed capacity allocated two times less memory and has better performance.

In conclusion I want to say, that I am perfectly aware that this example does not fit everywhere, because sometimes you just don’t know how much elements you would need. And the is totally fine. What I am saying is that you should always keep in mind the numbers above and when you instanciate a list, ask yourself if you cannot determine its size.

[Best Practice #1] Override the ToString() method of your classes

This is first of series of best practices and tips I have for my fellow software developers. The articles are not ordered by importance, they are completely random. (And I mean real random, not computer random)

There are a few methods available for you from the object class in .NET, which provide some basic functionalities for you structures. There’s a bunch of them, but giving definition and explanation for each one is not a target of our article. The one I am going to point out here is

public virtual string ToString()

Why this is important?

Well it is definitely not “a must”, but I have found it to be dramatically helpful during debugging. Let me show you why.

Imagine this simple class:

	public class Person
	{
		public Person(int id, string firstName, string lastName)
		{
			Id = id;
			FirstName = firstName;
			LastName = lastName;
		}

		public int Id { get; }
		public string FirstName { get; }
		public string LastName { get; }
	}

Now if I am doing some application, which populates a list of type List<Person>, by loading it from a database and I need to debug it, this is how my QuickWatch would look like:

As you can see, if I want to see the details of each object, in order to determine if some Person is there, I need to expand them one by one. Here I have only 5, but having a collection of thousands of items is not something unusual.

The trick that comes in handy is the previously mentioned ToString() method of the object base class. That method is there for a good reason. Whenever the .NET framework needs to convert some object into a textual representation, this is when that method is invoked. Also this method is used by tools like Visual Studio, to populate simple textbox based controls as the Value column we see in the screenshot.

Now let’s override our method in the Person class and then take a look at the QuickWatch. Here is our implementation:

	public override string ToString()
		{
			return $"[{Id}] {FirstName} {LastName}";
		}

As you can see, we are just returning somewhat meaningful string in that method. We are doing this by using string interpolation. By doing this, here is our new screenshot:

Here you can see, that our Value column looks much better now. I can see the text interpretation of our class here and not having to expand the objects in order to know, which object is the one with Id = 3.

Another place, where ToString() is used is in the string interpolation. Whenever you put an instance of an object in the curly brackets, the .NET is using the ToString() method in order to fill that. So if we have the following code:

Console.WriteLine($"The first person in the list is: {list[0]}");

This is the difference we have:

You see, if you don’t have a ToString() method overridden, this means that the default one will be used, that is implemented in the object class. And that one returns a string with the full class name.

With everything said, I want to show you how helpful that practice can be in your daily developer’s life. Debugging and writing things in the console is usually big part of what every developer does on a daily basis. Simply overriding the ToString() method can save you a lot of time and energy, and usually it is one line of code.

 

Programming Best Practices

In this series I will write some best practices that I have adopted and validated to be very useful, even critical sometimes, in my everyday’s life as a C# developer.

The guidelines I am talking about don’t necessarily apply only to C#, but this is the language I have most experience with.

I will start posting such an article every few days. And I will be more than happy to read your comments and suggestions about something I have missed or express your opinions against the ones I have put up here.

Of course I don’t consider my suggestions to be a silver bullet in programming, but I am applying those standards strictly and I do believe they are valid and work.

Below you will find list of articles with links, which I will update when a new article is published.

Best Practice #1: Override the ToString() method of your classes
Best Practice #2: Specify length of collections when you know it

Sharing folder between Google Drive users

Today I faced problem, for which the solution is not straight forward. I needed to have a folder, shared between computers at our company. Sounds pretty dull and normal. The trick is, that I want to have it shared even if I am not at the office. So I needed a Cloud solution. Since we use Google Apps at our company, the most useful solution would be to use Google Drive.

Here comes the issue. I know that I can share files and folders between Google users, doing it the old fashioned way, which was possible with Google Docs. Well you can achieve the above, but you need to make a few simple steps.

Step one

Create a folder on account “A”. Let’s call that folder “Cloud Share”

gdrive1

Step two

Go to your Google Drive Web access and share the folder with the account “B”, “C”, etc.

gdrive2

NOTE: Do not forget to give the user “Can edit” permission.

Step three

So far it is our old, well known sharing in Google Docs. But how do we show it in my Google Drive folder?

Well, it is pretty easy. You need to go to the Google Drive Web access on the account “B”, account “C”, etc. and go the the “Shared with me” section. Then check the shared folder and click “Add to My Drive”. And that’s it!

gdrive3

Now everything that anybody changes to this folder’s content will be synced between everybody. Great, easy and free way to collaborate files.

Lenovo Yoga 13 Review

Two days ago I blogged about my new laptop – The Lenovo Yoga 13”. Now here is the promised review, after using the Yoga for about 5 days already.

First look

The initial impression from the package is just great! Totally cool and sleek, bad-ass looking box! Lenovo are definitely learning from Apple in this direction. All of my older laptops came in very boring and cheap looking packages. This one looks expensive and high-end.

2013-02-15 12.15.552013-02-15 12.16.462013-02-15 12.17.08

The first look of the laptop itself is also great. The Yoga has nothing to do with the other older models that Lenovo (IBM) did. As we remember they are all cubical, ugly and looking like they came from 1980s.

2013-02-14 14.39.562013-02-14 14.38.56

Here this is not the case. The Yoga is very thin (just 16.9 mm). It has a nice matt finish. It is great looking piece of equipment.

2013-02-14 14.40.39

Note: The Yoga compared to my Samsung Galaxy Nexus

First boot

The Yoga comes with Windows 8 and to be honest this is my first real impression from it. And it is exactly as I expected – awesome! The touch screen is also a great improvement on top of that, which is working very nice, since it is a capacitive one.

The keyboard is very good and I can type quick and easy with it. The Enter key seems a little bit out of place and this leads to pressing the Home and End keys often, but it is not such a big issue.

On the sides of the touchpad the surface of the laptop is very soft and feels like rubber. In my opinion this is a good approach, since it is very comfortable on my hands while typing. Also I believe the main idea behind that rubber surface is so you can hold it easier while in tablet mode.

This is the next big thing about the Yoga. You can turn the screen around to 360 degrees, which transforms your laptop to a BIG 13.3 inch tablet. A little too huge and heavy for using as normal tablet, but I believe this won’t be the case. You won’t carry it around a lot and sit on the toilet with it, but for presentations and airplane tables it is more than perfect.

2013-02-14 14.39.112013-02-14 14.39.26

A lot of people complain that touching the keyboard on the back of your tablet-like laptop, is very strange and uncomfortable, but I don’t find it so problematic. There is a solution that Lenovo provides, which is a leather case for the keyboard while in tablet mode, but so far I don’t find it necessary.

Working with it

I have a lot of software that is heavy and that I use on regular basis. This includes Visual Studio 2012, Photoshop CS6, CorelDRAW X6, etc. I needed a computer that can handle all those pretty good. Well, the Yoga totally blew me away! I got the top model, which includes 8GB of RAM and 256GB SSD. It also has Intel i7 processor. All of this just chewed and swallowed the big hits that my heavy-load software threw at it. Everything starts up almost instantly and the cold boot of the laptop is measured in about 11 sec, from power button press to start menu loaded.

Playing with it

I am a passionate gamer. When I was choosing a computer, I knew that I could not get such a machine and expect it to be a gaming station. Still, I had some requirements. I do not play very heavy games like Call of Duty. The games I play are World of Warcraft, Star Wars: The Old Republic and Dota 2. So I want a computer that can run those in playable state. So far I have tried World of Warcraft and on medium details and High Performance plan on the laptop, I easily get 25-26 FPS, which is enough for normal play.

2013-02-14 14.55.09

Not everything is perfect

Of course there are some cons that I cannot miss. The battery is a little bit not enough. I can get about 4-4,5 hours out of it with normal usage like browsing, blogging, etc. If I get heavy and use the programs I need, I will probably drain it in less then 3 hours. I think this is not long enough.

Another con is the Windows key that is located below the screen. It is very strange to click, almost you can think that it is broken. I guess they haven’t spend too much time to improve that.

2013-02-14 14.39.34

Something else that bothers me is the touchpad. I find it to be a little bit unresponsive and not handling multitouch gestures very well. But most of the time I use a mouse or the touch screen, so this is also not a problem for me.

2013-02-14 14.39.45

Finally I notice that the cooling fan is working quite a lot. Maybe I am using a lot of stuff, but even now, while I am writing this article and have nothing else running, the cooling fan is blowing and I can hear it. This, I find to be annoying to some level.

Final words

To sum up, I would say that the Lenovo Yoga is an awesome machine and I definitely recommend it to everyone! I am incredibly satisfied with mine and I believe it is worth every penny.

2013-02-14 14.40.07

Fixing SkyDrive slow speed

Since some time I was thinking of buying additional space on one of my cloud storage providers. Currently I use DropBox (got 5,4GB so far), SkyDrive (7GB out of the box) and Google Drive (5GB). My favorites are DropBox and SkyDrive. Personally, I think Google Drive is still not very well done.

Looking at the pricings, from DropBox you can get 100GB for about $99 per year, while in SkyDrive, you get 100GB for about $49 per year. And it is even 107GB, since you keep the 7 GB free on top of the 100GB you pay for. This was a winner for me, but I had a problem. The uploading/downloading in SkyDrive is WAY much slower for me, than Dropbox’s. I started digging and it turns out there is a solution for that. Still under the hood one, but it worked for me and led to me buying the 100GB storage.

Here is the article, describing how to fix it: http://answers.microsoft.com/en-us/windowslive/forum/skydrive-sync/try-out-new-manual-configuration-for-improved/3e82447a-e852-4a5a-b06e-32dc8056a748#_self

My new gadget–Lenovo Yoga

Since I bought my iMac, I sold my Toshiba Qosmio and I did not have any portable computer besides my iPad. I thought that this is sufficient until I got to travel a few times abroad, with just the iPad. Yes, it is quite a great piece of hardware and I am able to do almost 95% of all my everyday tasks with it, but it is simply not enough.

I started researching the notebook/ultrabook/laptop market. I summed up my needs for a new portable computer to some basic guidelines:

  • It has to be thin – since carrying around the 8.8 mm thin iPad, getting some brick-like laptop was simply not going to be productive for me. So I knew I will be getting an ultrabook
  • It must have powerful processor – i5 at least! I know that most of my tasks that the laptop would need to cover, do not require so much CPU power, but in 20% of the cases, I do need it. Things like Photoshop and CorelDRAW, simply need to be running smooth.
  • It must have enough RAM – 6GB is my sanitary minimum. My iMac still has 4GB and that is killing me! I am planning to upgrade it in the near future. If you are interested how – here is a very nice tutorial.
  • It MUST be running Windows 8! Latest Windows, very cool, no need for more reasons.
  • Touch screen is very much appreciated – I believe this is the future of computers and Windows 8 is really much better with touch screen.
  • It MUST have SSD hard drive. I have spend way too long using traditional hard drives and suffering the killer slow performance they have.
  • Last, but not least is the price, of course. I don’t want to spend $2000-$2500 for a laptop (which is roughly the price of MacBook)

So, with those in mind, after browsing and after reading Scott Hanselman’s article about ultrabooks, I narrowed my search to only one ultrabook:

The Lenovo Yoga 13

This marvelous notebook combines all that I can desire in a portable computer. It has i7 processor, 8GB of RAM, Windows 8, touch screen and 256GB SSD. On top of that it looks great, it has a very sleek design and it is combination of ultrabook and tablet. I will give more details in the upcoming review, that I am writing, later this week. Best of all, it costs a little over $1600, including taxes and delivery.

All of this finally led to me, getting a new laptop. The astonishing Lenovo Yoga 13. So far I have been using it for 3 days and it is great!

UPDATE: Read my follow up review of the Lenovo Yoga 13

Got a new notebook

I am very happy to brag about my new notebook !

In the past few weeks I have been surfing the web looking for the ultimate notebook that will satisfy my needs as a gamer and developer, but let’s not forget also as a buyer who has to pay 🙂

How did I came to that idea ? Well, I have thrown away my desktop pc about 1 month ago. It was old, almost ancient. I have had it for almost 6 years already, so I came to the conclusion that is time to let it go. So I started thinking, if I should buy a new desktop pc. I really wanted something on which I can freely play games like Crysis and Mafia II. So I started digging. But I decided that I will look for some BIG notebook, instead of a desktop PC.

Why ? Well, because I already have a pretty 10” ASUS which I can carry around when I just need some PC and I can use the massive notebook to work, play and watch Full HD movies, but also be able to carry it around when I need it.

alienware m17x
AlienWare m17x

At first my attention landed on the EXCEPTIONAL AlienWare m17x.

Man this is some bad-ass machine. I thought I have found my notebook, BUT… when I saw the price starting at 5500 leva, I have quickly cooled off. Even tough I wanted such a monster, I really could not afford it.

So I continue searching and finally I got it. It is the Toshiba Qosmio X500-126 !

It is also a serious notebook. The Qosmio is part of the gaming line notebooks by Toshiba. And it is HUGE 🙂

toshiba
Toshiba Qosmio X500-126

It is 18.4” wide. Very big, nice Full HD screen. The beast is powered by Intel i7 (720QM) processor with normal speed of 1.60 GHz, but as most modern notebooks it jumps to 2.80 GHz on TURBO mode, or in other words, when you need it. It has 8GB of RAM, which is quite enough, but you definitely need a x64 bit operation system, because the 32bit one supports only 3GB max RAM. The video is NVIDIA GeForce GTS 360M, giving the enormous 1GB of dedicated memory.  The other specifications are pretty standard, but you can see them all here.

And I got all of this for 3300 leva. Definitely it is not cheap ! But it is worth every penny !

So I got it, and started playing. The experience is just UNIQUE ! The games are smooth, the display is great the sound is astonishing (with the Harman Kardon speakers) ! The keyboard is back-lid, which is GREAT for gaming in the dark !

The only problem I have so far is finding a suitable backpack in which to carry it around, but I will find some 🙂

LaserJet 1020 Accessed Over Network Problem

Today I stumbled upon a problem with my printer at home. I have HP LaserJet 1020. Very nice and productive home printer. The problem was the following:

I have a Windows XP desktop PC, to which the printer is connected and shared. My girlfriend’s PC is running Windows Vista and my Notebook is running Windows 7 (quite a diversity, I know). It turned out that I cannot install the printer on the Vista and 7. Every time I attended to, my spooler service crashed and that led to an error and abort of the installation. After a little bit of “Google research” I found out this great article by a guy named “inanis”. Here is the link.

I will also explain the steps that “inanis” gave:

• NOTE: Do this on the machine connected to the printer.
• Run gpedit.msc
• Go to “Local Computer Policies\Administrative Templates\Printers”
◦ Set the setting “Allow print spooler to accept client connections” to “Enabled”
• Go to “User Configuration\Administrative Templates\Control Panel\Printers\”
◦ Set the setting “Point and Print Restrictions” to “Disabled”
• Close the Group Policy Editor
• Go into the Printers and Faxes control panel, right click on the printer and hit properties.
• Click the “Ports” tab
• Uncheck “Enable Bidirectional Printing”
• Close the Printer panels/windows
• Run a command line, type in “gpupdate /force”, and hit enter