Search Results

Search found 4868 results on 195 pages for 'foreach'.

Page 4/195 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • What exactly does this PHP code do?

    - by Rob
    Alright, my friend gave me this code for requesting headers and comparing them to what the header should be. It works perfectly, but I'm not sure why. Here is the code: $headers = apache_request_headers(); $customheader = "Header: 7ddb6ffab28bb675215a7d6e31cfc759"; foreach ($headers as $header => $value) { // 1 $custom .= "$header: $value"; // 2 } $mystring = $custom; // 3 $findme = $customheader; // 4 $pos = strpos($mystring, $findme); if ($pos !== false) { // Do something } else{ exit(); } //If it doesn't match, exit. I commented with some numbers relating to the following questions: 1: What exactly is happening here? Is it setting the $headers as $header AND $value? 2: Again, don't have any idea what is going on here. 3: Why set the variable to a different variable? This is the only area where the variable is getting used, so is there a reason to set it to something else? 4: Same question as 3. I'm sorry if this is a terrible question, but its been bothering me, and I really want to know WHY it works. Well, I understand why it works, I guess I just want to know more specifically. Thanks for any insight you can provide.

    Read the article

  • How to make sure the value is reset in foreach loop in PHP

    - by kwokwai
    Hi all, I was writing a simple PHP page and a few foreach loops were used. Here are the scripts: $arrs = array("a", "b", "c"); foreach ($arrs as $arr) { if(substr($arr,0,1)=="b") { echo "This is b"; } } // ends of first foreach loop and I didn't use ifelse here And when this foreach ends, I wrote another foreach loop in which all the values in the foreach loop was the same as previous foreach. foreach ($arrs as $arr) { if(substr($arr,0,1)=="c") { echo "This is c"; } } I am not sure if it is a good practice to have two foreach loops with same values and keys. Will the values get overwritten in the first foreach loop?

    Read the article

  • Delaying a Foreach loop half a second

    - by Sigh-AniDe
    I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a foreach loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help this is what i tried : The foreach runs inside the update method DateTime dt = DateTime.Now; foreach ( string commandDirection in ghostMovements ) { int mapX = ( int )( ghostPostition.X / scalingFactor ); int mapY = ( int )( ghostPostition.Y / scalingFactor ); // If the dt is the same as current time if ( dt == DateTime.Now ) { if ( commandDirection == "left" ) { switch ( ghostDirection ) { case ghostFacingUp: angle = 1.6f; ghostDirection = ghostFacingRight; Program.form.direction = ""; dt.AddMilliseconds( 500 );// add half a second to dt break; case ghostFacingRight: angle = 3.15f; ghostDirection = ghostFacingDown; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingDown: angle = -1.6f; ghostDirection = ghostFacingLeft; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingLeft: angle = 0.0f; ghostDirection = ghostFacingUp; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; } } } }

    Read the article

  • How to ignore an exception and continue processing a foreach loop?

    - by Barry Dysert
    I have a test program that is supposed to loop over all the files under C:. It dies when it hits the "Documents and Settings" folder. I'd like to ignore the error and keep looping over the remaining files. The problem is that the exception is thrown in the foreach, so putting a try/catch around the foreach will cause the loop to exit. And putting a try/catch after the foreach never fires (because the exception is thrown in the foreach). Is there any way to ignore the exception and continue processing the loop? Here's the code: static void Main(string[] args) { IEnumerable<string> files = Directory.EnumerateFiles(@"C:\", "*.*", SearchOption.AllDirectories); foreach (string file in files) // Exception occurs when evaluating "file" Console.WriteLine(file); }

    Read the article

  • Is possible javascript code to extract c:forEach tag value?

    - by EswaraMoorthyNEC
    Hi, In my i have populate some values using c:forEach tag. I want to get those values in my javascript. If I click GetCtag value button, then i want to read (c:forEach)all values in javascript. Is any other-way to retrieve the c:forEach tag value <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> function getCTagValue(ctagObject) { alert("CFor Each Tag Object Value: " + ctagObject); // Here i want write code for retrieve the c:forEach tag value } </script> </head> <body> <h:form id="cTagForm" > <c:forEach items="${cTagBean.tagList}" var="ctag"> <c:out value="${ctag.name} : "/> <c:out value="${ctag.age}"/></br> </c:forEach> <a4j:commandButton id="GetCtagId" value="GetCtag" oncomplete="getCTagValue('#{cTagBean.tagList}')"/> </h:form> </body> </html> Help me. Thanks in advance.

    Read the article

  • Is possible : javascript extract value from c:forEach tag ?

    - by EswaraMoorthyNEC
    Hi, i have populate some values using c:forEach tag. I want to get those values in my javascript. If I click GetCtag value button, then i want to read from (c:forEach) values in javascript. Is any other-way to retrieve the c:forEach tag value <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> function getCTagValue(ctagObject) { alert("CFor Each Tag Object Value: " + ctagObject); // Here i want write code for retrieve the c:forEach tag value } </script> </head> <body> <h:form id="cTagForm" > <c:forEach items="${cTagBean.tagList}" var="ctag"> <c:out value="${ctag.name} : "/> <c:out value="${ctag.age}"/></br> </c:forEach> <a4j:commandButton id="GetCtagId" value="GetCtag" oncomplete="getCTagValue('#{cTagBean.tagList}')"/> </h:form> </body> </html> Help me. Thanks in advance.

    Read the article

  • How can I use nested Async (WCF) calls within foreach loops in Silverlight ?

    - by Peter St Angelo
    The following code contains a few nested async calls within some foreach loops. I know the silverlight/wcf calls are called asyncrously -but how can I ensure that my wcfPhotographers, wcfCategories and wcfCategories objects are ready before the foreach loop start? I'm sure I am going about this all the wrong way -and would appreciate an help you could give. private void PopulateControl() { List<CustomPhotographer> PhotographerList = new List<CustomPhotographer>(); proxy.GetPhotographerNamesCompleted += proxy_GetPhotographerNamesCompleted; proxy.GetPhotographerNamesAsync(); //for each photographer foreach (var eachPhotographer in wcfPhotographers) { CustomPhotographer thisPhotographer = new CustomPhotographer(); thisPhotographer.PhotographerName = eachPhotographer.ContactName; thisPhotographer.PhotographerId = eachPhotographer.PhotographerID; thisPhotographer.Categories = new List<CustomCategory>(); proxy.GetCategoryNamesFilteredByPhotographerCompleted += proxy_GetCategoryNamesFilteredByPhotographerCompleted; proxy.GetCategoryNamesFilteredByPhotographerAsync(thisPhotographer.PhotographerId); // for each category foreach (var eachCatergory in wcfCategories) { CustomCategory thisCategory = new CustomCategory(); thisCategory.CategoryName = eachCatergory.CategoryName; thisCategory.CategoryId = eachCatergory.CategoryID; thisCategory.SubCategories = new List<CustomSubCategory>(); proxy.GetSubCategoryNamesFilteredByCategoryCompleted += proxy_GetSubCategoryNamesFilteredByCategoryCompleted; proxy.GetSubCategoryNamesFilteredByCategoryAsync(thisPhotographer.PhotographerId,thisCategory.CategoryId); // for each subcategory foreach(var eachSubCatergory in wcfSubCategories) { CustomSubCategory thisSubCatergory = new CustomSubCategory(); thisSubCatergory.SubCategoryName = eachSubCatergory.SubCategoryName; thisSubCatergory.SubCategoryId = eachSubCatergory.SubCategoryID; } thisPhotographer.Categories.Add(thisCategory); } PhotographerList.Add(thisPhotographer); } PhotographerNames.ItemsSource = PhotographerList; } void proxy_GetPhotographerNamesCompleted(object sender, GetPhotographerNamesCompletedEventArgs e) { wcfPhotographers = e.Result.ToList(); } void proxy_GetCategoryNamesFilteredByPhotographerCompleted(object sender, GetCategoryNamesFilteredByPhotographerCompletedEventArgs e) { wcfCategories = e.Result.ToList(); } void proxy_GetSubCategoryNamesFilteredByCategoryCompleted(object sender, GetSubCategoryNamesFilteredByCategoryCompletedEventArgs e) { wcfSubCategories = e.Result.ToList(); }

    Read the article

  • How do I use foreach with QDomNodeList in Qt?

    - by Venemo
    Hi Everyone, I'm new to Qt and I'm learning something new every day. Currently, I'm developing a small application for my Nokia N900 in my free time. Everything is fine, I am able to compile and run Maemo applications on the device. I've just learned about the foreach keyword in Qt. (I know it is not in C++, so I didn't think about it until I accidentally stumbled upon a Qt doc that mentioned it.) So, I decided to change my quite annoying and unreadable loops to foreach, but I failed with this: QDomNodeList list = doc.lastChild().childNodes().at(1).firstChild().childNodes(); for (int x = 0; x < list.count(); x++) { QDomElement node = list.at(x).toElement(); // Do something with node } This is how I tried: foreach (QDomElement node, doc.lastChild().childNodes().at(1).firstChild().childNodes()) { // Do something with node } For some reason the above code doesn't even compile. I get cryptic error messages from the compiler. Could someone please explain to me how to get it right? If the foreach loop doesn't support QDomNodeList, is there a way of handling XML files that do support foreach?

    Read the article

  • Can I use foreach to return only a certain type from a collection?

    - by RoboShop
    If I enter the code below, I get an error. Basically, the foreach will break when it comes across a Control that isn't a label. foreach (Label currControl in this.Controls()) { ... } I have to do something like this. foreach (Control currControl in this.Controls()) { if(typeof(Label).Equals(currControl.GetType())){ ... } } can anyone think of a better way of doing it without me needing to check the type? Can I somehow get foreach to skip the objects that aren't Labels?

    Read the article

  • what use does the javascript forEach method have (that map can't do)?

    - by JohnMerlino
    Hey all, The only difference I see in map and foreach is that map is returning an array and foreach is not. However, I don't even understand the last line of the foreach method "func.call(scope, this[i], i, this);". For example, isn't "this" and "scope" referring to same object and isn't this[i] and i referring to the current value in the loop? I noticed on another post someone said "Use forEach when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects". I don't know what is meant by side effects. Array.prototype.map = function(fnc) { var a = new Array(this.length); for (var i = 0; i < this.length; i++) { a[i] = fnc(this[i]); } return a; } Array.prototype.forEach = function(func, scope) { scope = scope || this; for (var i = 0, l = this.length; i < l; i++) func.call(scope, this[i], i, this); } Finally, are there any real uses for these methods in javascript (since we aren't updating a database) other than to manipulate numbers like this: alert([1,2,3,4].map(function(x){ return x + 1})); //this is the only example I ever see of map in javascript. Thanks for any reply.

    Read the article

  • XNA 2D Top Down game - FOREACH didn't work for checking Enemy and Switch-Tile

    - by aldroid16
    Here is the gameplay. There is three condition. The player step on a Switch-Tile and it became false. 1) When the Enemy step on it (trapped) AND the player step on it too, the Enemy will be destroyed. 2) But when the Enemy step on it AND the player DIDN'T step on it too, the Enemy will be escaped. 3) If the Switch-Tile condition is true then nothing happened. The effect is activated when the Switch tile is false (player step on the Switch-Tile). Because there are a lot of Enemy and a lot of Switch-Tile, I have to use foreach loop. The problem is after the Enemy is ESCAPED (case 2) and step on another Switch-Tile again, nothing happened to the enemy! I didn't know what's wrong. The effect should be the same, but the Enemy pass the Switch tile like nothing happened (They should be trapped) Can someone tell me what's wrong? Here is the code : public static void switchUpdate(GameTime gameTime) { foreach (SwitchTile switch in switchTiles) { foreach (Enemy enemy in EnemyManager.Enemies) { if (switch.Active == false) { if (!enemy.Destroyed) { if (switch.IsCircleColliding(enemy.EnemyBase.WorldCenter, enemy.EnemyBase.CollisionRadius)) { enemy.EnemySpeed = 10; //reducing Enemy Speed if it enemy is step on the Tile (for about two seconds) enemy.Trapped = true; float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds; moveCounter += elapsed; if (moveCounter> minMoveTime) { //After two seconds, if the player didn't step on Switch-Tile. //The Enemy escaped and its speed back to normal enemy.EnemySpeed = 60f; enemy.Trapped = false; } } } } else if (switch.Active == true && enemy.Trapped == true && switch.IsCircleColliding(enemy.EnemyBase.WorldCenter, enemy.EnemyBase.CollisionRadius) ) { //When the Player step on Switch-Tile and //there is an enemy too on this tile which was trapped = Destroy Enemy enemy.Destroyed = true; } } } }

    Read the article

  • forEach and Facelets - a bugfarm just waiting for harvest

    - by Duncan Mills
    An issue that I've encountered before and saw again today seems worthy of a little write-up. It's all to do with a subtle yet highly important difference in behaviour between JSF 2 running with JSP and running on Facelets (.jsf pages). The incident I saw today can be seen as a report on the ADF EMG bugzilla (Issue 53) and in a blog posting by Ulrich Gerkmann-Bartels who reported the issue to the EMG. Ulrich's issue nicely shows how tricky this particular gochya can be. On the surface, the problem is squarely the fault of MDS but underneath MDS is, in fact, innocent. To summarize the problem in a simpler testcase than Ulrich's example, here's a simple fragment of code: <af:forEach var="item" items="#{itemList.items}"> <af:commandLink id="cl1" text="#{item.label}" action="#{item.doAction}"  partialSubmit="true"/> </af:forEach> Looks innocent enough right? We see a bunch of links printed out, great. The issue here though is the id attribute. Logically you can kind of see the problem. The forEach loop is creating (presumably) multiple instances of the commandLink, but only one id is specified - cl1. We know that IDs have to be unique within a JSF component tree, so that must be a bad thing?  The problem is that JSF under JSP implements some hacks when the component tree is generated to transparently fix this problem for you. Behind the scenes it ensures that each instance really does have a unique id. Really nice of it to do so, thank you very much. However, (you could see this coming), the same is not true when running with Facelets  (this is under 11.1.2.n)  in that case, what you put for the id is what you get, and JSF does not mess around in the background for you. So you end up with a component tree that contains duplicate ids which are only created at runtime.  So subtle chaos can ensue.  The symptoms are wide and varied, from something pretty obscure such as the combination Ulrich uncovered, to something as frustrating as your ActionListener just not being triggered. And yes I've wasted hours on just such an issue.  The Solution  Once you're aware of this one it's really simple to fix it, there are two options: Remove the id attribute on components that will cause some kind of submission within the forEach loop altogether and let JSF do the right thing in generating them. Then you'll be assured of uniqueness. Use the var attribute of the loop to generate a unique id for each child instance.  for example in the above case: <af:commandLink id="cl1_#{item.index}" ... />.  So one to watch out for in your upgrades to JSF 2 and one perhaps, for your coding standards today to prepare you for. For completeness, here's the reference to the underlying JSF issue that's at the heart of this: JAVASERVERFACES-1527

    Read the article

  • Multiple Sprites using foreach Collison Detection in XNA (C#)

    - by Bradley Kreuger
    Back again from my last question. Now I was curious I use a foreach statement to use the same shot class. How would I go about doing collison detection. I used the tutorial here on how to shoot a fireball http://www.xnadevelopment.com/tutorials.shtml. I tried to put in several places a foreach to look at all of them to see if they have reached the borders of my sprite hero but doesn't seem to do anything. If again some one might know of a good site that has tutorials to explain collision detection a little bit better that would be appriecated.

    Read the article

  • foreach() error handling - how do make it do nothing?

    - by Jared
    Hey all, This should be very basic, but I am a little stumped! Here is my array: $menu = array( 'Home', 'Stuff'=>array( 'Losta Stuff', 'Less Stuff', 'Ur moms stuff', 'FAQ' ), 'Public Works' ); Here is my logic: echo "<ol>\n"; foreach( (array)$menu as $header ) { echo ' <li><b>'.$header."</b><br />\n"; echo ' <ol>'; foreach( (array)$header as $headers ) { echo ' <li>'.$headers.".</li>\n"; } echo ' </ol>'; } echo "</ol>\n"; As you can see, Home and Public Works don't have data in the them, so I get a Warning: Invalid argument supplied for foreach() in test.php on line ## If I add (array) to $header like this: foreach( (array)$header as $headers ), It no longer gives me the error, but it just displays the $header as the $headers (i.e. Home - Home, Instead of Home - nothing). Basically, if the data is empty, I want it to do nothing!

    Read the article

  • In .NET which loop runs faster for or foreach

    - by Binoj Antony
    In c#/VB.NET/.NET which loop runs faster for or foreach? Ever since I read that for loop works faster than foreach a long time ago I assumed it stood true for all collections, generic collection all arrays etc. I scoured google and found few articles but most of them are inconclusive (read comments on the articles) and open ended. What would be ideal is to have each scenarios listed and the best solution for the same e.g: (just example of how it should be) for iterating an array of 1000+ strings - for is better than foreach for iterating over IList (non generic) strings - foreach is better than for Few references found on the web for the same: Original grand old article by Emmanuel Schanzer CodeProject FOREACH Vs. FOR Blog - To foreach or not to foreach that is the question asp.net forum - NET 1.1 C# for vs foreach [Edit] Apart from the readability aspect of it I am really interested in facts and figures, there are applications where the last mile of performance optimization squeezed do matter.

    Read the article

  • How can I use an Ant foreach iteration with values from a file?

    - by Egon Willighagen
    In our Ant build environment, I have to do the same task for a number of items. The AntContrib foreach task is useful for that. However, the list is in a parameter, where I actually have the list in a file. How can I iterate over items in a file in an foreach-like way in Ant? Something like (pseudo-code): <foreach target="compile-module" listFromFile="$fileWithModules"/> I'm happy to write a custom Task, and welcome any suggestion on possible solutions.

    Read the article

  • PHP: Is there an elegant way to foreach through multiple items (groups) at a time?

    - by acheong87
    Given an array of N items: $arr = array('a', 'b', 'c', 'd', 'e', 'f'); What's the most elegant way to loop through in groups of M items (assuming N is divisible by M)? I tried foreach (array_chunk($arr, 2) as list($first, $second)) { // do stuff with $first and $second } but this resulted in a syntax error. In other words, I want to emulate what in Tcl would look like this: set arr [a b c d e f] foreach {first second} $arr { // do stuff with $first and $second } For now I've resorted to the obvious measure: foreach (array_chunk($arr, 2) as $group) { $first = $group[0]; $second = $group[1]; // do stuff with $first and $second } But I'm hoping someone has a more elegant method...

    Read the article

  • How can I use foreach and fork together to do something in parallel?

    - by kaushalmodi
    This question is not UVM specific but the example that I am working on is UVM related. I have an array of agents in my UVM environment and I would like to launch a sequence on all of them in parallel. If I do the below: foreach (env.agt[i]) begin seq.start(env.agt[i].sqr); end , the sequence seq first executes on env.agt[0].sqr. Once that gets over, it then executes on env.agt[1].sqr and so on. I want to implement a foreach-fork statement so that seq is executed in parallel on all agt[i] sequencers. No matter how I order the fork-join and foreach, I am not able to achieve that. Can you please help me get that parallel sequence launching behavior? Thanks.

    Read the article

  • C#: LINQ vs foreach - Round 1.

    - by James Michael Hare
    So I was reading Peter Kellner's blog entry on Resharper 5.0 and its LINQ refactoring and thought that was very cool.  But that raised a point I had always been curious about in my head -- which is a better choice: manual foreach loops or LINQ?    The answer is not really clear-cut.  There are two sides to any code cost arguments: performance and maintainability.  The first of these is obvious and quantifiable.  Given any two pieces of code that perform the same function, you can run them side-by-side and see which piece of code performs better.   Unfortunately, this is not always a good measure.  Well written assembly language outperforms well written C++ code, but you lose a lot in maintainability which creates a big techncial debt load that is hard to offset as the application ages.  In contrast, higher level constructs make the code more brief and easier to understand, hence reducing technical cost.   Now, obviously in this case we're not talking two separate languages, we're comparing doing something manually in the language versus using a higher-order set of IEnumerable extensions that are in the System.Linq library.   Well, before we discuss any further, let's look at some sample code and the numbers.  First, let's take a look at the for loop and the LINQ expression.  This is just a simple find comparison:       // find implemented via LINQ     public static bool FindViaLinq(IEnumerable<int> list, int target)     {         return list.Any(item => item == target);     }         // find implemented via standard iteration     public static bool FindViaIteration(IEnumerable<int> list, int target)     {         foreach (var i in list)         {             if (i == target)             {                 return true;             }         }           return false;     }   Okay, looking at this from a maintainability point of view, the Linq expression is definitely more concise (8 lines down to 1) and is very readable in intention.  You don't have to actually analyze the behavior of the loop to determine what it's doing.   So let's take a look at performance metrics from 100,000 iterations of these methods on a List<int> of varying sizes filled with random data.  For this test, we fill a target array with 100,000 random integers and then run the exact same pseudo-random targets through both searches.                       List<T> On 100,000 Iterations     Method      Size     Total (ms)  Per Iteration (ms)  % Slower     Any         10       26          0.00046             30.00%     Iteration   10       20          0.00023             -     Any         100      116         0.00201             18.37%     Iteration   100      98          0.00118             -     Any         1000     1058        0.01853             16.78%     Iteration   1000     906         0.01155             -     Any         10,000   10,383      0.18189             17.41%     Iteration   10,000   8843        0.11362             -     Any         100,000  104,004     1.8297              18.27%     Iteration   100,000  87,941      1.13163             -   The LINQ expression is running about 17% slower for average size collections and worse for smaller collections.  Presumably, this is due to the overhead of the state machine used to track the iterators for the yield returns in the LINQ expressions, which seems about right in a tight loop such as this.   So what about other LINQ expressions?  After all, Any() is one of the more trivial ones.  I decided to try the TakeWhile() algorithm using a Count() to get the position stopped like the sample Pete was using in his blog that Resharper refactored for him into LINQ:       // Linq form     public static int GetTargetPosition1(IEnumerable<int> list, int target)     {         return list.TakeWhile(item => item != target).Count();     }       // traditionally iterative form     public static int GetTargetPosition2(IEnumerable<int> list, int target)     {         int count = 0;           foreach (var i in list)         {             if(i == target)             {                 break;             }               ++count;         }           return count;     }   Once again, the LINQ expression is much shorter, easier to read, and should be easier to maintain over time, reducing the cost of technical debt.  So I ran these through the same test data:                       List<T> On 100,000 Iterations     Method      Size     Total (ms)  Per Iteration (ms)  % Slower     TakeWhile   10       41          0.00041             128%     Iteration   10       18          0.00018             -     TakeWhile   100      171         0.00171             88%     Iteration   100      91          0.00091             -     TakeWhile   1000     1604        0.01604             94%     Iteration   1000     825         0.00825             -     TakeWhile   10,000   15765       0.15765             92%     Iteration   10,000   8204        0.08204             -     TakeWhile   100,000  156950      1.5695              92%     Iteration   100,000  81635       0.81635             -     Wow!  I expected some overhead due to the state machines iterators produce, but 90% slower?  That seems a little heavy to me.  So then I thought, well, what if TakeWhile() is not the right tool for the job?  The problem is TakeWhile returns each item for processing using yield return, whereas our for-loop really doesn't care about the item beyond using it as a stop condition to evaluate. So what if that back and forth with the iterator state machine is the problem?  Well, we can quickly create an (albeit ugly) lambda that uses the Any() along with a count in a closure (if a LINQ guru knows a better way PLEASE let me know!), after all , this is more consistent with what we're trying to do, we're trying to find the first occurence of an item and halt once we find it, we just happen to be counting on the way.  This mostly matches Any().       // a new method that uses linq but evaluates the count in a closure.     public static int TakeWhileViaLinq2(IEnumerable<int> list, int target)     {         int count = 0;         list.Any(item =>             {                 if(item == target)                 {                     return true;                 }                   ++count;                 return false;             });         return count;     }     Now how does this one compare?                         List<T> On 100,000 Iterations     Method         Size     Total (ms)  Per Iteration (ms)  % Slower     TakeWhile      10       41          0.00041             128%     Any w/Closure  10       23          0.00023             28%     Iteration      10       18          0.00018             -     TakeWhile      100      171         0.00171             88%     Any w/Closure  100      116         0.00116             27%     Iteration      100      91          0.00091             -     TakeWhile      1000     1604        0.01604             94%     Any w/Closure  1000     1101        0.01101             33%     Iteration      1000     825         0.00825             -     TakeWhile      10,000   15765       0.15765             92%     Any w/Closure  10,000   10802       0.10802             32%     Iteration      10,000   8204        0.08204             -     TakeWhile      100,000  156950      1.5695              92%     Any w/Closure  100,000  108378      1.08378             33%     Iteration      100,000  81635       0.81635             -     Much better!  It seems that the overhead of TakeAny() returning each item and updating the state in the state machine is drastically reduced by using Any() since Any() iterates forward until it finds the value we're looking for -- for the task we're attempting to do.   So the lesson there is, make sure when you use a LINQ expression you're choosing the best expression for the job, because if you're doing more work than you really need, you'll have a slower algorithm.  But this is true of any choice of algorithm or collection in general.     Even with the Any() with the count in the closure it is still about 30% slower, but let's consider that angle carefully.  For a list of 100,000 items, it was the difference between 1.01 ms and 0.82 ms roughly in a List<T>.  That's really not that bad at all in the grand scheme of things.  Even running at 90% slower with TakeWhile(), for the vast majority of my projects, an extra millisecond to save potential errors in the long term and improve maintainability is a small price to pay.  And if your typical list is 1000 items or less we're talking only microseconds worth of difference.   It's like they say: 90% of your performance bottlenecks are in 2% of your code, so over-optimizing almost never pays off.  So personally, I'll take the LINQ expression wherever I can because they will be easier to read and maintain (thus reducing technical debt) and I can rely on Microsoft's development to have coded and unit tested those algorithm fully for me instead of relying on a developer to code the loop logic correctly.   If something's 90% slower, yes, it's worth keeping in mind, but it's really not until you start get magnitudes-of-order slower (10x, 100x, 1000x) that alarm bells should really go off.  And if I ever do need that last millisecond of performance?  Well then I'll optimize JUST THAT problem spot.  To me it's worth it for the readability, speed-to-market, and maintainability.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >