SolvedPrivate

Is this an "expensive" operation?

Posted on 2015-01-06
6
44 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 34

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 34

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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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 34

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
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…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

615 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