SolvedPrivate

Is this an "expensive" operation?

Posted on 2015-01-06
6
38 Views
Last Modified: 2016-02-17
I got help from an EE member and I used it. Someone here says it's "an expensive" operation. Is it?

 public bool ValidateSubmission(ConsumerModel model)
        {
            
            //1. check if productId, PromotionId and Serial number exist 
            var p = (....
                select s);

            if (p.Any()) //row exists
                throw new ArgumentException("some message here");

      //3 more checks like this here

Open in new window


I call it like this

 try
                    {
                        _repository.ValidateSubmission(model); 
                    }

Open in new window

0
Comment
Question by:Camillia
  • 3
  • 3
6 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 40534141
If you are checking against p 4 times, then yes, it is an expensive operation.  Consider the following (for illustrative purposes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EE_Q28591670
{
	class Program
	{
		static List<SomeObject> data = new List<SomeObject>();

		static void Main(string[] args)
		{
			SomeObject result = null;
			var watch = new Stopwatch();
			for (int i = 0; i < 1000000; i++)
				data.Add(new SomeObject() { ID = i, Name = string.Format("SomeName{0}", i), Created = DateTime.Now.AddDays(i), IsActive = (i % 2) == 0 });

			watch.Start();
			ValidateSubmission(99999);
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("ValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			result = GetSpecificRecord(99999);
			watch.Stop();
			Console.WriteLine("GetSpecificRecord took {0}ms.", watch.ElapsedMilliseconds);
			Console.ReadLine();
		}

		private static void ValidateSubmission(int id)
		{
			var p = (from item in data select item);

			if (p.Any(x => x.ID.Equals(id)))
				Console.WriteLine("Found ID in set = {0}", p.Where(x => x.ID.Equals(id)).FirstOrDefault().ID);

			if (p.Any(x => x.Name.Contains(id.ToString())))
				Console.WriteLine("Found Name in set = {0}", p.Where(x => x.Name.Contains(id.ToString())).FirstOrDefault().Name);

			if (p.Any(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)))
				Console.WriteLine("Found Date in set = {0:MM/dd/yyyy}", p.Where(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)).FirstOrDefault().Created);
		}

		private static SomeObject GetSpecificRecord(int id)
		{
			return (from item in data where item.ID.Equals(id) select item).SingleOrDefault();
		}
	}

	class SomeObject
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Created { get; set; }
		public bool IsActive { get; set; }
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
0
 
LVL 7

Author Comment

by:Camillia
ID: 40534155
It's checking against 4 LINQ statements (I should've been clear). Below. Would that make a difference?

 var p = (.....
                select s);

            if (p.Any()) //row exists
                throw new ArgumentException("msg here");

                  
            
            var x = (......
                select s);

            if (!x.Any())
                throw new ArgumentException("msg here");

               var y = (......
                select s);
            if (!y.Any())
                throw new ArgumentException("msg here");

            //4. if product selected is not in promotion
            var y1 = (....
                select s);

            if (!y1.Any())
                throw new ArgumentException("some msg here");

            return true;

Open in new window

0
 
LVL 33

Expert Comment

by:it_saige
ID: 40534178
The more linq statements you check against, the more costly your operation becomes.  This is because specifying:
var y1 = (from foo in bar where someCriteria() select foo)

Open in new window

Does not actually do anything except setup an Enumerator.  It's only when you do something:
if (!y1.Any())

Open in new window

That you access the enumeration to validate the condition.  And it should be implied that whenever you access the enumeration, you are performing a loop operation.

If you look at my example, I only used one linq statement but I looped through the enumeration 6 times.  For comparison consider the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EE_Q28591670
{
	class Program
	{
		static List<SomeObject> data = new List<SomeObject>();

		static void Main(string[] args)
		{
			SomeObject result = null;
			var watch = new Stopwatch();
			for (int i = 0; i < 1000000; i++)
				data.Add(new SomeObject() { ID = i, Name = string.Format("SomeName{0}", i), Created = DateTime.Now.AddDays(i), IsActive = (i % 2) == 0 });

			watch.Start();
			ValidateSubmission(99999);
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("ValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			result = GetSpecificRecord(99999);
			watch.Stop();
			Console.WriteLine("GetSpecificRecord took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			EfficientValidateSubmission(99999);
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("EfficientValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.ReadLine();
		}

		private static void ValidateSubmission(int id)
		{
			var p = (from item in data select item);

			if (p.Any(x => x.ID.Equals(id)))
				Console.WriteLine("Found ID in set = {0}", p.Where(x => x.ID.Equals(id)).FirstOrDefault().ID);

			if (p.Any(x => x.Name.Contains(id.ToString())))
				Console.WriteLine("Found Name in set = {0}", p.Where(x => x.Name.Contains(id.ToString())).FirstOrDefault().Name);

			if (p.Any(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)))
				Console.WriteLine("Found Date in set = {0:MM/dd/yyyy}", p.Where(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)).FirstOrDefault().Created);
		}

		private static void EfficientValidateSubmission(int id)
		{
			var p = (from item in data where item.ID.Equals(id) && item.Name.Contains(id.ToString()) && item.Created.Date.Equals(DateTime.Now.AddDays(id).Date) select item).FirstOrDefault();

			if (p != null)
			{
				Console.WriteLine("Found ID in set = {0}", p.ID);
				Console.WriteLine("Found Name in set = {0}", p.Name);
				Console.WriteLine("Found Date in set = {0:MM/dd/yyyy}", p.Created);
			}
		}

		private static SomeObject GetSpecificRecord(int id)
		{
			return (from item in data where item.ID.Equals(id) select item).SingleOrDefault();
		}
	}

	class SomeObject
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Created { get; set; }
		public bool IsActive { get; set; }
	}
}

Open in new window

Which produces the following results -Capture.JPG-saige-

P.S. - And in case you are wondering why there is a discrepency in EfficientValidationSubmission vs GetSpecifiedRecord.  It is because GetSpecifiedRecord uses SingleOrDefault (which has to look at every object in the enumeration to ensure that there is only one object that matches the search criteria); whereas EfficientValidationSubmission uses FirstOrDefault() (which returns the first object).
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 7

Author Comment

by:Camillia
ID: 40534188
This guy says the issue for being it expensive is that I used throw instead of just returning a string back. True?
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40534217
It is true that throwing exceptions can be more costly than result based returns.

Exceptions and Performance

And for proof of concept, consider the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EE_Q28591670
{
	class Program
	{
		static List<SomeObject> data = new List<SomeObject>();

		static void Main(string[] args)
		{
			SomeObject result = null;
			var watch = new Stopwatch();
			for (int i = 0; i < 1000000; i++)
				data.Add(new SomeObject() { ID = i, Name = string.Format("SomeName{0}", i), Created = DateTime.Now.AddDays(i), IsActive = (i % 2) == 0 });

			watch.Start();
			ValidateSubmission(99999);
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("ValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			result = GetSpecificRecord(99999);
			watch.Stop();
			Console.WriteLine("GetSpecificRecord took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			EfficientValidateSubmission(99999);
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("EfficientValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			try
			{
				ExceptionValidateSubmission(99999);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("ExceptionValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.WriteLine();
			watch.Reset();
			watch.Start();
			Console.WriteLine(ResultValidateSubmission(99999));
			watch.Stop();
			Console.WriteLine();
			Console.WriteLine("ResultValidateSubmission took {0}ms.", watch.ElapsedMilliseconds);
			Console.ReadLine();
		}

		private static void ValidateSubmission(int id)
		{
			var p = (from item in data select item);

			if (p.Any(x => x.ID.Equals(id)))
				Console.WriteLine("Found ID in set = {0}", p.Where(x => x.ID.Equals(id)).FirstOrDefault().ID);

			if (p.Any(x => x.Name.Contains(id.ToString())))
				Console.WriteLine("Found Name in set = {0}", p.Where(x => x.Name.Contains(id.ToString())).FirstOrDefault().Name);

			if (p.Any(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)))
				Console.WriteLine("Found Date in set = {0:MM/dd/yyyy}", p.Where(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)).FirstOrDefault().Created);
		}

		private static void ExceptionValidateSubmission(int id)
		{
			var p = (from item in data select item);

			if (p.Any(x => x.ID.Equals(id)))
				throw new Exception(string.Format("Found ID in set = {0}", p.Where(x => x.ID.Equals(id)).FirstOrDefault().ID));

			if (p.Any(x => x.Name.Contains(id.ToString())))
				throw new Exception(string.Format("Found Name in set = {0}", p.Where(x => x.Name.Contains(id.ToString())).FirstOrDefault().Name));

			if (p.Any(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)))
				throw new Exception(string.Format("Found Date in set = {0:MM/dd/yyyy}", p.Where(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)).FirstOrDefault().Created));
		}

		private static string ResultValidateSubmission(int id)
		{
			var p = (from item in data select item);

			if (p.Any(x => x.ID.Equals(id)))
				return string.Format("Found ID in set = {0}", p.Where(x => x.ID.Equals(id)).FirstOrDefault().ID);

			if (p.Any(x => x.Name.Contains(id.ToString())))
				return string.Format("Found Name in set = {0}", p.Where(x => x.Name.Contains(id.ToString())).FirstOrDefault().Name);

			if (p.Any(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)))
				return string.Format("Found Date in set = {0:MM/dd/yyyy}", p.Where(x => x.Created.Date.Equals(DateTime.Now.AddDays(id).Date)).FirstOrDefault().Created);

			return string.Empty;
		}

		private static void EfficientValidateSubmission(int id)
		{
			var p = (from item in data where item.ID.Equals(id) && item.Name.Contains(id.ToString()) && item.Created.Date.Equals(DateTime.Now.AddDays(id).Date) select item).FirstOrDefault();

			if (p != null)
			{
				Console.WriteLine("Found ID in set = {0}", p.ID);
				Console.WriteLine("Found Name in set = {0}", p.Name);
				Console.WriteLine("Found Date in set = {0:MM/dd/yyyy}", p.Created);
			}
		}

		private static SomeObject GetSpecificRecord(int id)
		{
			return (from item in data where item.ID.Equals(id) select item).SingleOrDefault();
		}
	}

	class SomeObject
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Created { get; set; }
		public bool IsActive { get; set; }
	}
}

Open in new window

Produces the following output -Capture.JPG-saige-
0
 
LVL 7

Author Comment

by:Camillia
ID: 40534249
Thanks. I'll  change the code and review your examples
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

937 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

1 Experts available now in Live!

Get 1:1 Help Now