|
Judah Himango wrote: from least to greatest,
which Array.Reverse could fix; and I wouldn't be surprised when the Sort+Reverse combination would prove to be faster than all the new and fancy stuff...
Luc Pattyn [Forum Guidelines] [My Articles]
- before you ask a question here, search CodeProject, then Google
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get
- use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets
|
|
|
|
|
If it's faster, it's likely a miniscule difference. Also consider that OrderByDescending is delay executed, and since this guy needs only the first element, it's probably faster in this case than doing separate array operations that touch all the elements twice.
But since we're nitpicking, I'd say that
var greatest = ints.OrderByDescending(i => i).First();
is clearer than
Array.Sort(ints);
Array.Reverse(ints);
int greatest = ints[0];
Intent is clearer, and allows for more advanced abstractions, such as the forthcoming PLINQ.
Of course, all this is probably zero relevance for this guy asking the question, since he just wants the greatest element in an array. That we're nitpicking is the only reason I bring it up!
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
There is no need to reverse anything if all required is the largest value, just sort and pick the last value; or don't sort and just traverse once keeping track of the largest so far, as in:
int max=int.MinValue;
foreach(int i in ints) if(max<i) max=i;
assuming the compiler is smart enough to enumerate the array without actually creating an enumerator, this should work without any method call and be the fastest way to get it done.
If not, use good old for and an index...
As for readability the only one really acceptable is int max=ints.Largest; which AFAIK is not yet supported; extension methods is one thing, how about extension properties?
Luc Pattyn [Forum Guidelines] [My Articles]
- before you ask a question here, search CodeProject, then Google
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get
- use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets
|
|
|
|
|
(I'm amused by this thread, as we've so wildly veered off helping this guy and are now deeply engaged in an irrelevant, pseudo-friendly programming pissing match! )
Is the compiler smart enough to convert that into a for loop? Otherwise we have the overhead of allocating an iterator, making a manual for loop being the fastest (or at least, requiring the fewest allocations).
Of course, we're trading readability for fewer allocations in the hopes of better performance, trading our nice declarative code for very detailed imperative code that's hard to optimize, since we're being so specific about how we want the results, rather than declaring the results we want.
In this era of 4 and 8 core desktop machines, with 32 cores coming in the next 5 years, perhaps the fastest and most readable will be:
var greatest = ints.AsParallel().OrderByDescending(i => i).First();
Oh hell yes.
Your move.
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
Judah Himango wrote: we've so wildly veered off helping this guy
Didn't he get ample help for his quest? Can't help it he only needed a little bit of help, the matter deserves deeper examination.
Judah Himango wrote: era of 4 and 8 core desktop machines
no matter what amount of hardware resources you throw at the problem at hand, performing a full sort when none is required cannot possibly be the winning strategy. If you want to parallelize (new word?) the quest for the largest number, just split the data set over the cores, and pick the largest of all the largests. BTW: that is of course what int max=ints.Largest; is supposed to do.
Anyway, 2 to 4 threads is fine for my needs; most of the additional ones we will have in future will be very busy performing utilitarian stuff such as:
- aggregating the latest MSDN help info;
- RSS feeding different web sites, trying to keep up with all the CP forums and the like;
- scanning for viruses;
- automatically reporting WPF bugs;
- downloading and installing fixes for Visual Studio and the like (excluding WPF, that one is unfixable from the start according to JSOP).
Luc Pattyn [Forum Guidelines] [My Articles]
- before you ask a question here, search CodeProject, then Google
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get
- use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets
|
|
|
|
|
Luc Pattyn wrote: BTW: that is of course what int max=ints.Largest; is supposed to do.
Ah. Ok then, I give up. When will you be writing an article that introduces extension properties added to C# 3 and the new array.Largest extension property?
Luc Pattyn wrote: Anyway, 2 to 4 threads is fine for my needs; most of the additional ones we will have in future will be very busy performing utilitarian stuff such as:
Indeed...
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
Judah Himango wrote: When will you be writing an article
When the new stuff becomes available and only if MSDN fails to document it properly.
I'll try and come up with some other article topics in the mean time...
Luc Pattyn [Forum Guidelines] [My Articles]
- before you ask a question here, search CodeProject, then Google
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get
- use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets
|
|
|
|
|
Judah Himango wrote: opposite of what he's looking for.
Well, not really. Since he wants the greatest, he just needs to know whether to get it from array[0] or array[array.Length(-1?)], once it is sorted.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
|
|
|
|
|
More than one way to skin a cat.
Likewise, you could use
var greatest = ints.OrderBy(i => i).Last();
I'd argue the LINQ way is more declarative, the intent is clearer, and allows for more advanced abstractions. Whatever the case, though, it probably doesn't matter to the guy asking the question.
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
modified on Thursday, April 2, 2009 12:08 PM
|
|
|
|
|
Judah Himango wrote: More than one way to skin a cat
First you have to catch it.
Good job he's using .Net.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
|
|
|
|
|
How to create table using rectangle in pictureBox1???
Thanks before...
Iman Ridwan
|
|
|
|
|
Hook up to the pictureBox.Paint event. Inside the event handler, you can draw whatever you like onto the picture box using the Graphics[^] object passed in the event args.
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
Hi all,
Is there any build in string comparison or filter method that could ignore escaped character(like /r/n) & html tags(like <br> )?
I've tried the regular expression like "Regex.Replace(xml, "\\.", "");" for escape characters, but it didn't work.
Thanks,
<div class="ForumMod">modified on Wednesday, April 1, 2009 11:11 PM</div>
|
|
|
|
|
There isn't such a thing built in the .NET framework class libraries.
You could build your own like this:
public static string GetStringWithoutEscapedSequences(string input)
{
var escapedSequences = new[] { "\r\n", "<br>" };
foreach(var sequence in escapedSequences)
{
input = input.Replace(sequence, string.Empty);
}
return input;
}
Then compare your strings like this:
var first = GetStringWithoutEscapedSequences(strA);
var second = GetStringWithoutEscapedSequences(strB);
var areEqual = string.Equals(first, second);
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
I have a form with a particularly slow loading process. To acheive a more responsive UI I decided to use a seperate thread to load the data and populate the datagridview.
If called direct the form takes 10 secondes to display.
I have a separate method called LoadGrid to do that work.
The following is called in the form_load method
Thread oThread = new Thread(new ThreadStart(LoadGrid));
oThread.IsBackground = true;
oThread.Start();
LoadCombos();
UIUtils.BindObject(this, cashFlow);
/pre>
My expectation is that the form will display, the user can manipulate the controls and the DGV will load 10 seconds after the form is initiated. This does not happen, I get a partial display and the form locks, 10 seconds later the form completes loading and releases the UI.
Where am I screwing it up.
The LoadGrid is correctly delegated and the thread is invoked properly,
<pre> private delegate void LoadGridDelegate();
private void LoadGrid()
{
try
{
if (this.InvokeRequired)
{
this.BeginInvoke(new LoadGridDelegate(LoadGrid), null);
}
else
{
DataTable dtAttr = cashFlow.GetAttrForCashflow(cashFlow.CashflowID);
UIUtils.dgLoad(dgAttr, dtAttr.DefaultView, "");
}
}
catch (Exception)
{ throw; }
}
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Try calling grid.Update() after invoking.
Also, don't catch the Exception if you're just gonna throw it.
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
The grid is not a problem, it updates correctly when the data is returned. The issue is that the rest of the form also waits for the thread to complete before it finishes form_load.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Your problem is that the UI thread is still doing the main work. You spawn a thread, and when that thread executes, it simply delegates the work back onto the UI thread. Woops.
Assuming that getting the DataTable is the part that's freezing your UI, here's what the correct code should look like, using the recommended pattern of the BackgroundWorker component.
class Form1 : Form
{
public Form1()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (sender, e) =>
{
e.Result = cashFlow.GetAttrForCashflow(cashFlow.CashflowID);
};
worker.RunWorkerCompleted += (sender, e) =>
{
var dataTable = (DataTable)e.Result;
UIUtils.dgLoad(dataTable, dataTable.DefaultView, "");
};
worker.RunWorkerAsync();
}
}
Religiously blogging on the intarwebs since the early 21st century: Kineti L'Tziyon
Judah Himango
|
|
|
|
|
Thanks Judah, I pinched Navaneeths solution.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Your LoadGrid method has the problem..
private void LoadGrid()
{
try
{
if (this.InvokeRequired)
{
this.BeginInvoke(new LoadGridDelegate(LoadGrid), null);
Now <code>InvokeRequired</code> will be false and else conditions executes.
}
else
{
DataTable dtAttr = cashFlow.GetAttrForCashflow(cashFlow.CashflowID);
UIUtils.dgLoad(dgAttr, dtAttr.DefaultView, "");
}
}
catch (Exception)
{ throw; }
} Here is the corrected code,
private void LoadGrid()
{
DataTable dtAttr = cashFlow.GetAttrForCashflow(cashFlow.CashflowID);
this.BeginInvoke((MethodInvoker)delegate
{
UIUtils.dgLoad(dgAttr, dtAttr.DefaultView, "");
});
}
|
|
|
|
|
Magic stuff - exactly what I was expecting from my code crap. Now to do some research on MethodInvoker
Thanks a lot!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Mycroft Holmes wrote: Now to do some research on MethodInvoker
It's just a delegate which can point to any method which will have no parameters.
|
|
|
|
|
[MSDN]This API supports the .NET Framework infrastructure and is not intended to be used directly from your code[/MSDN]
This would normally make me leery of using it.
N a v a n e e t h wrote: method which will have no parameters.
I presume this limitation is the reason it is not recommended. In which case the background solution will need to looked into as well.
Thanks.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
In that case you can create your own delegate with required parameters. I have seen many applications using MethodInvoker when you need to invoke a simple parameter-less method. I am not sure why MSDN say's not to use it.
|
|
|
|
|
Hi Mycroft,
getting the DataTable is what takes most of 10 seconds and needs to be delegated to a thread.
Your LoadGrid() method uses Invoke to cause the GUI thread to do it anyway, so your efforts to speed up things are pointless so far.
Here is unchecked code to get the DataTable on the thread and the DGV update on the UI thread;
it does not rely on any fancy C# code, it should work on all .NET versions:
private void LoadGrid(DataTable dtAttr) {
if (this.InvokeRequired) {
dtAttr = cashFlow.GetAttrForCashflow(cashFlow.CashflowID);
this.BeginInvoke(new LoadGridDelegate(LoadGrid), dtAttr );
} else {
UIUtils.dgLoad(dtAttr, dtAttr.DefaultView, "");
}
}
With anonymous methods/delegates you can further simplify it as others have shown.
Luc Pattyn [Forum Guidelines] [My Articles]
- before you ask a question here, search CodeProject, then Google
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get
- use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets
|
|
|
|