.net - Faster Way To Convert From A String To Generic Type T When T Is A Valuetype?
Jan 6, 2011
Does anyone know of a fast way in VB to go from a string to a generic type T constrained to a valuetype (Of T as Structure), when I know that T will always be some number type?This is too slow for my taste:
Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T)
But it seems to be the only sane method of getting from a String --> T. I've tried using Reflector to see how Convert.ChangeType works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T so it can be returned.
I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T) value. If I strongly-type my class for a specific number type (i.e., UInt16), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use.
It'd almost be nice if there was converter to/from T while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?
Conclusion:Testing the three provided implementations below and my original DirectCast/ChangeType form, @peenut's approach of using a prepared delegate to fetch the Parse method from a basic type works. No error checking is done, however, so implementors need to remember to only use this with valuetypes that have a Parse method available. Or extend the below to do error checking.
All runs were done on a 32bit system running Windows Server 2003 R2 with 4GB of RAM. Each "run" is 1,000,000 executions (ops) of the method to be tested, timed with StopWatch and reported back in milliseconds.
Original DirectCast(Convert.ChangeType(myStr, GetType(T)), T):
1000000 ops: 597ms
Average of 1000000 ops over 10 runs: 472ms
Average of 1000000 ops over 10 runs: 458ms
[code]....
Using System.Reflection and calling InvokeMethod to get at the Parse method:
1000000 ops: 12213ms
Average of 1000000 ops over 10 runs: 11468ms
Average of 1000000 ops over 10 runs: 11509ms
Average of 1000000 ops over 10 runs: 11524ms
[code]....
Konrad's approach to generate IL code to access the Parse method and store the call into a delegate:
1000000 ops: 352ms
Average of 1000000 ops over 10 runs: 316ms
Average of 1000000 ops over 10 runs: 315ms
[code]....
peenut's approach of using a delegate to access the Parse method directly:
1000000 ops: 272ms
Average of 1000000 ops over 10 runs: 272ms
Average of 1000000 ops over 10 runs: 275ms
[code]....
Comparatively, peenut's approach is almost 200ms faster when executed 1,000,000 times in a tight loop, so his approach wins out. Although, Konrad's wasn't far behind and is itself a fascinating study of things like ILGenerator.
View 4 Replies
ADVERTISEMENT
May 1, 2012
fast way in VB to go from a string to a generic type T constrained to a valuetype (Of T as Structure), when I know that T will always be some number type?This is too slow for my taste:
Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T)
But it seems to be the only sane method of getting from a String --> T. I've tried using Reflector to see how Convert.ChangeType works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T so it can be returned.
I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T) value. If I strongly-type my class for a specific number type (i.e., UInt16), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use.
It'd almost be nice if there was converter to/from T while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?
Conclusion:Testing the three provided implementations below and my original DirectCast/ChangeType form, @peenut's approach of using a prepared delegate to fetch the Parse method from a basic type works. No error checking is done, however, so implementors need to remember to only use this with valuetypes that have a Parse method available. Or extend the below to do error checking.
All runs were done on a 32bit system running Windows Server 2003 R2 with 4GB of RAM. Each "run" is 1,000,000 executions (ops) of the method to be tested, timed with StopWatch and reported back in milliseconds.
Original DirectCast(Convert.ChangeType(myStr, GetType(T)), T):
1000000 ops: 597ms
Average of 1000000 ops over 10 runs: 472ms
Average of 1000000 ops over 10 runs: 458ms
[code]....
Comparatively, peenut's approach is almost 200ms faster when executed 1,000,000 times in a tight loop, so his approach wins out.
View 32 Replies
Jan 13, 2011
In VB.NET 2010, how to return a boolean value as generic type without compile warning?
View 2 Replies
Dec 17, 2009
what's the main difference between a Class and a Type and a ValueType.and is a Delegate a Type? or an eventhandler/event (the actual event itself)is every object a type? or is it only true in VB
View 3 Replies
Jul 21, 2011
I've got this function:
Public Shared Function GetQueryStringValue(Of T As Structure)(ByVal queryStringVariable As String) As T
Dim queryStringObject As Nullable(Of T) = Nothing
If queryStringVariable <> Nothing Then
If HttpContext.Current.Request.QueryString(queryStringVariable) IsNot Nothing Then
queryStringObject = DirectCast(HttpContext.Current.Request.QueryString(queryStringVariable), T)
End If
[Code]...
View 2 Replies
May 23, 2010
Using the following code:
[Code]...
View 6 Replies
Nov 19, 2010
i am getting all filenames from a directory.parsing out the directory names & the .vb extension then converting those filesnames to classes.Every file in the LPCriteria direcotry is its own class with a "Evaluate" function.[code]
View 1 Replies
Apr 13, 2012
Consider:
Public MustInherit Class Column
Public ReadOnly Property ReturnSomethingUseful() As Object
Get
'return something useful
[code]....
But this gives the following error:
Public Overrides Function ParseValue(sValue As String) As Boolean'
cannot override 'Public Overridable Function ParseValue(sValue As String) As Object'
because they differ by their return types.
I accept that you can't do this, but I'd like to be able to preserve the semantics of what I'm. trying to do, which is to have an untyped version that deals with Object, but a typed version in derived classes that knows about the specific type T.
View 2 Replies
Aug 28, 2009
In a VS 2008 ASP.net 3.5 aspx.vb file, Response.Write(DDL.SelectedItem) worked very well.But "Dim filenameDDL As String = DDL.SelectedItem.Text" did not. Then I tried the following codes and found the problem -- Conversion from type 'ListItem' to type 'String' is not valid.
[Code]...
View 1 Replies
Feb 12, 2011
This code:
vb Dim s As String = strContents '<a global variable) Dim currentPos As Int64 = 0 Dim endPos As Int64 = strContents.Length - 1 '// A dictionary, used to count the frequencies Dim characterCounter As New Dictionary(Of [String], Int64)() While currentPos <> endPos '//
[CODE]...
Gives this error: Value of type 'System.Collections.Generic.KeyValuePair(Of String, Long)' cannot be converted to 'System.Collections.DictionaryEntry'.
View 2 Replies
Aug 14, 2010
I have a Journal that records entries for different types: Journal(Of ParentT)
[Code]....
View 2 Replies
Jun 30, 2011
I am trying to create a list of a generic type in vb.net 2.0 framework.
This is the generic type definition:
Public Class GenericParamMap(Of T)
Public Sub New(ByVal pParamName As String, ByVal pPropValue As T)
mParamName = pParamName
[Code]....
The compiler does not allow a "T" in the method's parameter because it's not defined, but I'm not sure how or where to define it. I thought it was okay to have a generic method definition.
View 2 Replies
Feb 8, 2012
I am trying to write a generic method, to avoid code duplication, which will create or activate a Form as an MDI children, based on its type. But I have to lines in error (see comments).
[Code]...
View 4 Replies
Jun 12, 2010
. I get this error: "Cannot convert lambda expression to type 'string' because it is not a delegate type" - keyword select become underlined in blue
[Code]...
Above code should displays drop list of employees first name and last name in a combo box
View 2 Replies
Apr 23, 2012
What is the quickest way to convert a string value of a URL to type URI? VB.NET please..
View 2 Replies
Mar 6, 2010
I need a function that will convert a type to a string, for example[code]...
View 2 Replies
Jan 3, 2011
Is there are any way to convert boolean type into "ON"/"OFF" using string formatter
Like:
Dim inpValue as Boolean
Dim outValue = String.Format("0:ON;OFF", inpValue)
' should show OFF as output
I cannot use code or IFormatProvider
View 6 Replies
Feb 22, 2012
I have a field in the database that is XML because it represents a class that is used in C#/VB.Net. Problem is after the initial manipulation most, but not all, of themanipulation is done in SQL Server. This means that the XML field is converted on the fly.As we are getting more fields and more records, this operation is getting slow. I think the slow down is the converting all of those fields to other data types.So to speed it up I was thinking of a couple of ways:Have a set of tables that represent the different pieces of the XML data. I would make these tables read only using a trigger on Insert/Update that would reject any changes. My 'main' table with the XML in it when it updates the XML would turn off the triggers, update the tables with the new values then turn the triggers back on.
The only real reason we use the XML is because it's really easy to convert it to the class in C#/VB.Net. But I'm getting the point where I may end up writing a routine that will take all the bits and pieces and convert it to a class and also a function to go the other way (class -> tables).
View 2 Replies
May 5, 2009
I'm compiling a VB.Net 2.0 app (created in VS2008) using msbuild, and now I've added a generic return type, it's giving me the following:
Warning: Type library exporter encountered a generic type instance in a signature. Generic code may not be exported to COM.
Having just spent ages removing all of the previous warnings, I don't really want to add a new one. Any idea how to get rid of it (aside from not using generics)?I don't know what details I'd put in the attribute, or what number to put in the project-level ignore list.
View 1 Replies
Sep 12, 2011
I have a question about ASP.Net, visual basic I have 2 LINQ query's, the first one works, the second one doesnt, produces a
"Unable to cast object of type 'System.Data.Objects.ObjectQuery'1[SelmaV2.Products]' to type 'System.Collections.Generic.List'1[System.String]'.
[Code]....
View 1 Replies
Dec 14, 2011
I have a generic Class I'm using to hold information loaded from a database.I have a method which takes a DataRow as an argument, uses the object's known column name and extracts the data from the DataRow, such that:Dim loadData As T = CType(myDataRow("myColumnName"), T))works as my default assignment in most cases.Unfortunately, due to some horrifying design constraints, some of my columns may be null, and may also be taken from enumerations.This means that when <T> is Nullable(Of SomeEnumeration) the above code does not work because I can't cast 0 directly to SomeEnumeration.Zero.Is there some way to check whether <T> is Nullable(Of [Enum])? Or some way to write a method which allows Integers to be cast to Nullable(Of [Enum])?I feel like I'm forgetting something that would allow me to write one of the other of these, but my weak google-fu is turning up nothing.
EDIT: Okay, thanks to dasblinkenlight's answer below, I can detect when this circumstance is occurring, but what I need to do now is to take a type <T> which I know is Nullable(Of SomeClass), get a type reference to SomeClass and then create a new object of type Nullable(Of SomeClass) and assign that to LoadData.My problem was that I had a lot of difficulty in finding any function which would accept baseType as an actual Type.Parse accepted baseType as a parameter, I knew baseType was an [Enum] type because of dasblinkenlight's code, so I was, in this instance, able to code a solution. It's a solution which is very specific to my problem (i.e., T is Nullable(of SomeEnumeration)), but it's a solution nonetheless.
View 2 Replies
Feb 14, 2012
In trying to add a bit of usage variety to a generic class I'm working on, I ran into this issue with trying to cast an object into an interface instance where the interface is defined inside the generic class.
[Code]...
View 1 Replies
Mar 30, 2010
1) VB Allows non-type template parameters2) VB supports explicit specialization 3) VB allows the type parameters to be used as the base class for the generic type4) VB allows a generic type parameter itself to to be a generic 5) VB enforces that all codes are valid for all types of parametrs
View 1 Replies
Jun 7, 2011
i am working in windows appl vb.net 08. And i am working in Access DataBase.I have one Table Called "Person" . In this "Person" Table one Column Name Called "OtherName". In this Column binded in one of the Combobox in a Form.But the Problem is "OtherName" Column having the Null Values.Before i bind this Column to Combobox i want to convert this NULL Values to String. Why i need the values in STRING means , In my code i using this Combobox as a filter in SQL Query.If i didn`t change the Null Value to STRING , The Combobox SelectedText or SelectedValue is Showing Nothing. So i am not able to get the Record.
Whn i write a Sql Query to Combobox and apply filter in WHERE statement like Combobox.Selectedtext or Combobox.SelectedValue In "Selected Change Committed Event" then i should get the record in the Output right but unfortunatly i am not getting the Record. The Record Count in DebugPrint showing 0.
[Code]...
View 6 Replies
Feb 17, 2011
Value of type 'System.Func(Of String, String)' cannot be converted to 'System.Converter(Of String, String)
Why? They are both effectively a function pointer (or delegate?) to a function that accept a string and return a string.
View 6 Replies
Sep 17, 2009
I accidently wrote some code today that was like this[code]...
I immediately noticed the issue, but I had already hit the run button. It compiled successfully, I ran it through to the section and it threw an exception.
You can't do this in C#, it gives a compile error "cannot convert from 'int?' to 'int'".
Is there an 'Option Explicit' type switch that I can turn on to ensure that this sort of error does not occur again?
View 1 Replies
May 14, 2012
I'm getting an error after sending a list to a web service.This is the code that is calling the web service:
Dim sProgramInterest As New List(Of Integer)
crmService.InsertProspectGetId(sProgramInterest.ToList)
But I'm getting this error.
[code].....
View 3 Replies
Jan 7, 2012
And here is the code that produces the error
CODE:
How can i cast this one?
View 1 Replies
Nov 17, 2011
I was using a JSON MAKER class to make a JSON string to send off from my webservice - it was way too slow - so I thought I would do the string manipulation right in the recordset loop - how could I go wrong - it is only 1141 records![code]...
View 10 Replies
May 7, 2012
I am using two textBox's. The first to enter the data. The second to convert to answer the program complies with no error, the debugger cannot convert data type from string to double.
[Code]....
why does the program not convert the textbox txtFahrenheit from string to double?
View 6 Replies