Menu
  • HOME
  • TAGS

How does .NET optimize methods that return a Structure value?

Tag: .net,vb.net

Consider a method that returns a Structure, like this:

Public Function DoWork() As MyStructure

    Return New MyStructure(1.5, 1.7, 1.1, 55.9)

End Function

In this case, does .NET create and initialize a MyStructure value once, or twice?

EDIT: My hunch is that a call to DoWork must involve .NET pushing the return value on the stack right from the outset. Otherwise, how would Return get anything back to the calling code? So that's the first initialization I'm talking about.

The second initialization would be at the Return statement, where arguments 1.5, 1.7, 1.1, 55.9 initialize a new MyStructure value. On Return, .NET would then overwrite the existing value on the Stack with the new return value.

The thing is, I know very little about how .NET works under the hood. My conception of how Stacks work is based on vague recollections of trying to code in Pascal, under DOS, in the early 90s. I have no idea how .NET/Windows does things these days!

Best How To :

Just have a look at the generated machine code to see what happens. You first need to change an option to ensure the optimizer is enabled, Tools > Options > Debugging > General > untick the "Suppress JIT optimization" checkbox. Switch to the Release build. Set a breakpoint on the DoWork call and when it hits use Debug > Windows > Disassembly to see the generated machine code.

I'll noodle a little bit about what you see. Your instinct is correct, only returning simple scalar values is efficient, they fit in a CPU register. Not this structure, the caller method must reserve space on its stack frame so the callee can store the structure there. It passes a pointer to that reserved space. In other words, there's no real difference if you had declared this method as Public Sub DoWork(ByRef retval As MyStructure).

Only other way this code can be optimized is by inlining the Function. The x86 jitter does not do that, it is picky about methods returning structs. The x64 jitter does in fact inline the method, but then does an absolutely horrible job with it. It still reserves the space for the return value and then generates lots and lots of needless initialization and value moving code. Quite atrocious. This jitter was rewritten for VS2015 (project name RyuJIT), I don't have it installed yet to see if it does a better job at it.

Basic conclusion to draw: this code isn't optimized. Structures work well when you pass them ByVal. Don't let this cramp your style, we're talking nanoseconds here.

Is Serialization the same as GetBytes?

.net

No, GetBytes() just converts a string to its binary represenation using the asked encoding. So it does serialize, but it is very specific to strings. When you want to serialize any object to bytes, you could use the BinaryFormatter. More about how to serialize an object using the BinaryFormatter can...

Return index of word in string

arrays,vb.net,vbscript

Looking at your desired output it seems you want to get the index of word in your string. You can do this by splitting the string to array and then finding the item in an array using method Array.FindIndex: Dim animals = "cat, dog, bird" ' Split string to array...

Visual Basic Datagrid View change row colour

vb.net,datagridview,datagrid

Is it possible that your datagridview isn't loaded fully when you try to recolor the rows? Since you are setting the datasource, you should put your code that affects the grid after you can make sure that it is finished loading. The column widths change because it is not dependent...

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

Related entity not loaded

c#,.net,entity-framework

Mark your relation property with virtual keyword for EF's proxy to be able to overload it: [ForeignKey("SchoolClassId")] public virtual SchoolClass SchoolClass { get; set; } Also, be sure that context's DbContext.Configuration.ProxyCreationEnabled property value is set to true (by default it is). These two conditions enabling lazy loading of your relations....

Capturing group recursively inside non-capturing group?

.net,regex

The .net regex implementation gives the possibility to store the substrings of a repeated capture group. So with this pattern that describes the whole string: \A(?:(\d+(?:-\d+)?)(?:,|\z))+\z (where \A and \z stand for the start and the end of the string) you obtain all the values in capture group 1 with...

String Format: How to add any number of zeros before string

c#,.net

int num = 4; string a = num.ToString("D4"); Documentation...

inconsistent timing from .net StopWatch

c#,.net,timing,stopwatch,cudafy.net

As the TotalMilliseconds is constantly incrementing & you are trying to find differences between points in time, you need to subtract the sum of the preceding differences after the second one, hence : tIQR = watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum); & tThresholdOnly= watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum + tIQR); ...

Convert date to string format

vb.net,converter

Your approach doesn't work because you are using ToString on a DataColumn which has no such overload like DateTime. That doesn't work anyway. The only way with the DataTable was if you'd add another string-column with the appropriate format in each row. You should instead use the DataGridViewColumn's DefaultCellStyle: InvestorGridView.Columns(1).DefaultCellStyle.Format...

Connecting to database using Windows Athentication

sql-server,vb.net,authentication,connection-string

You need to add Integrated Security=SSPI and remove username and password from the connection string. Dim ConnectionString As String = "Data Source=Server;Initial Catalog=m2mdata02;Integrated Security=SSPI;" ...

Microsoft Band and WPF

.net,wpf,dll,microsoft-band,.net-core

The current Band SDK does not support Windows desktop (i.e. Win32) applications. It supports only Windows Store and Windows Phone (i.e. WinRT) applications. Portable libraries can be confusing as the terms '.NETCore' and 'netcore451' refer to the Windows Store version of the .NET framework....

Get XML node value when previous node value conditions are true (without looping)

xml,vb.net,linq-to-xml

UPDATE Using an XDocument vs an XmlDocument, I believe this does what you're asking without using loops. This is dependent on the elements being in the order of <PhoneType> <PhonePrimaryYN> <PhoneNumber> string xml = "<?xml version=\"1.0\"?>" + "<Root>" + " <PhoneType dataType=\"string\">" + " <Value>CELL</Value>" + " </PhoneType>" + "...

ZipEntry() and converting persian filenames

vb.net,persian,sharpziplib

Try setting IsUnicodeText to true: 'VB.NET Dim newEntry = New ZipEntry(entryName) With { _ Key .DateTime = DateTime.Now, _ Key .Size = size, _ Key .IsUnicodeText = True _ } //C# var newEntry = new ZipEntry(entryName) { DateTime = DateTime.Now, Size = size, IsUnicodeText = true }; ...

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of...

XElement.Value is stripping XML tags from content

c#,.net,xml,xml-parsing,xelement

As others have said, this format is truly horrible, and will break as soon as the XML embedded in the JSON will contain double quotes (because in the JSON they will be encoded as \", which will make the XML invalid). The JSON should really be embedded as CDATA. Now,...

Unconstrained type parameters casting

c#,.net,types,casting

The compiler sees the T2 and T identifiers and helpfully informs you that those types seem unrelated. That's absolutely correct, as they have no relation: there are no generic constraints that would assert any relations between them (I'm not saying that would be useful here though :) ). Whether this...

Unhandled exceptions and background workers

.net,exception-handling,backgroundworker

The other threads will carry on. Only the thread used by the BackgroundWorker will crash. An unhandled exception will be thrown. Since there is no exception handling in the event handler, it will get caught by the CLR as a last resort. This will not influence other threads....

Retrieve full path of FTP file on drag & drop?

vb.net,ftp

If the data dropped contains a UniformResourceLocator format, you can get the entire URL from that, for example: Private Sub Form1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop If e.Data.GetDataPresent("UniformResourceLocator") Then Dim URL As String = New IO.StreamReader(CType(e.Data.GetData("UniformResourceLocator"), IO.MemoryStream)).ReadToEnd End If End Sub It first checks to see if a...

Can't output Guid Hashcode

sql,vb.net,guid,hashcode

Well, are you looking for a hashcode like this? "OZVV5TpP4U6wJthaCORZEQ" Then this answer might be useful: Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=",""); GuidString = GuidString.Replace("+",""); Extracted from here. On the linked post there are many other useful answers. Please take a look! Other useful links:...

Visual Studio Assembly force-installs Target Framework

c#,.net,visual-studio-2013,.net-framework-version

The targeted .NET version is the only version that the app will depend upon by default. Visual Studio will not automatically add higher and backwards compatible releases. Do this manually by adding other .NET versions to a configuration file: On the Visual Studio menu bar: Choose Project; Add New Item;...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model

You need to pass the model instance to the view: Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View(employee) End Function ...

How does convert.ToString(C0) behave?

c#,.net

You can brute force search the string for any currency symbols and change them to whatever character you want eg: string s = "$"; foreach (var c in s) { var category = CharUnicodeInfo.GetUnicodeCategory(c); if (category == UnicodeCategory.CurrencySymbol) { //Force convert the char to what every character you want }...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface

If i have understood it correctly you want to get all selected parents and all selected children. You could use a recursive method: Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes) Get Return rootList.Where(Function(t) t.SelectedInTreeSelector). SelectMany(Function(root) GetSelectedChildren(root)). ToList() End Get End Property Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean =...

Filtering Last Duplicate Occurrence In A Datatable

c#,vb.net

You can use LINQ: DataTable nonDups = parsedDataset.Tables("Detail").AsEnumerable() .GroupBy(row => row.Field<string>("Authorization_ID")) .OrderBy(grp => grp.Key) .Select(grp => grp.Last()) .CopyToDataTable(); This selects the last row of each dup-group. If you want to order the group use grp.OrderBy....

DialogBox with value verifications

c#,.net,winforms

The problem is you're trying to enable or disable the button when checking individual textboxes and they're conflicting with each other, instead the logic needs to be at a higher level. Change your textbox validation function to return a bool, and use that in ValidateAll to determine whether or not...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

how can i use parameters to avoid sql attacks

sql,vb.net

I think the only solution is create a new function and gradually migrate to it. Public Function ExecuteQueryReturnDS(ByVal cmdQuery As SqlCommand) As DataSet Try Dim ds As New DataSet Using sqlCon As New SqlConnection(connStr) cmdQuery.Connection = sqlCon Dim sqlAda As New SqlDataAdapter(cmdQuery) sqlAda.Fill(ds) End Using Return ds Catch ex As...

check if a list contains all the element in an array using linq

vb.net,linq

You can use Enumerable.All: dim linqMeddata = From m In medicineDataList Where keys.All(Function(k) m.MedicineData.Contains(k)) Order By m.MedicineName Ascending Select m ...

Feature-specific compatibility of a .NET 4.5 application on a system with .NET 4.0

c#,.net,zipfile

The easiest way to do this is probably to load the required code dynamically. You could use reflection to look for the required assembly, class and members if .NET 4.5 is detected. You could cache the results in delegates, to avoid reflecting every time. You could also use a plug-in...

How do I use VB.NET to send an email from an Outlook account?

vb.net,email

change the smtpserver from smtp.outlook.com to smtp-mail.outlook.com web.config settings <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network host="smtp-mail.outlook.com" userName="[email protected]" password="passwordhere" port="587" enableSsl="true"/> </smtp> </mailSettings> ...

External Datepicker not working

javascript,jquery,.net

Apparently your Array has no map method, which is part of ECMA-262 edition 5 and which your JS engine seems not to support? You can implement Array.prototype.map manually by taking it from somewhere like https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

how can I add a column to IQueryable object and modify its values

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Removing Alert When Using DeleteFile API

vb.net,vba,api,delete

There are several SHFILEOPSTRUCT.fFlags options you'll want to consider. You are asking for FOF_NOCONFIRMATION, &H10. You probably want some more, like FOF_ALLOWUNDO, FOF_SILENT, FOF_NOERRORUI, it isn't clear from the question. Check the docs.

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor

That's probably a good candidate for an EditorTemplate to be honest, that way you don't have any issues with prefixing: @Html.EditorFor(m => m.TechnologyFilters) Without using an editor template though, a technique you can use is to specify the prefix in your partial declaration within the ViewDataDictionary, by doing: Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters,...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...

Formatting large numbers in C#

c#,.net,unity3d,formatting

I am using this method in my project, you can use too. Maybe there is better way, I dont know. public void KMBMaker( Text txt, double num ) { if( num < 1000 ) { double numStr = num; txt.text = numStr.ToString() + ""; } else if( num < 1000000...

QUERY IN C# ,where statement

c#,.net,select

I Assumed that you are using SQL this a generic query for your question: SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME= '" + combobox1.Text + "'"; here is what I recommend SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=...

How to pass all value of ListBox Control to a function?

vb.net,listbox

You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting. You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

c#,.net,windows,sendkeys

I believe you need to use: SendKeys.SendWait("^(s)"); Instead of: SendKeys.SendWait("^%s?"); Have a look at https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx for more information....

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0

Yes. If the operation completed without errors you are guaranteed that the documents have an ID (either created by you before the operation or by the driver in the operation itself). Moreover, since the IDs are generated by the driver itself (client-side) before calling the MongoDB server there's a good...

How can I determine if an object of anonymous type is empty?

c#,.net

Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations. Use the static object.Equals, method which will do the appropriate null checks and then call...

Syntax error in Insert query in Mysql in VB.Net

mysql,vb.net

you miss the closing parenthesis for the values list: Dim cmd1 As New OdbcCommand("insert into party values('" + pcode_txt.Text + "','" + Trim(UCase(name_txt.Text)) + "','" + Trim(UCase(addr_txt.Text)) + "','" + phone_txt.Text + "','" + combo_route.SelectedItem + "','" + combo_area.SelectedItem + "')", con) My answer is perfectly fit to your question...

Application is missing required files

c#,.net,windows,winforms,sharpdevelop

Your program is looking for compas.ico inside the build directory, while it probably resides in some other directory in your project.

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

VB.Net DateTime conversion

jquery,vb.net,datetime

System.Globalization.DateTimeFormatInfo.InvariantInfo doesn't contain format pattern dd-MM-yyyy(26-06-2015) From MSDN about InvariantCulture The InvariantCulture property can be used to persist data in a culture-independent format. This provides a known format that does not change For using invariant format in converting string to DateTime your string value must be formatted with one of...