dotnet clr:
Hi there guys,
Here is the code snippet which in which i am trying to read a file and
taking two cases in first one i promote the object to Gen1 so that it
will be saved from frequent Gen0 Collections and dont have to read file
again which is a costly business.In second case, normal process without
promoting.So trying to prove that first case works faster
Module Module1
Sub main()
Dim objTest1 As New Test1
Dim someNumber As Integer = 500
Dim i As Integer
Dim t As DateTime
Dim CurrentTime As DateTime
t = DateTime.Now
For i = 0 To 100000
objTest1.ReadFile()
Next
CurrentTime = DateTime.Now
Console.WriteLine(String.Format("Time taken with promotion:
{0}:{1}", CurrentTime.Subtract(t).Seconds,
CurrentTime.Subtract(t).Milliseconds))
Console.WriteLine("File Read: {0} times",
TextFile._fileReadCount)
TextFile._fileReadCount = 0
Dim objTest2 As Test1 = New Test1
t = DateTime.Now
For i = 0 To 100000
If (i Mod someNumber = 0 AndAlso i > 0) Then
GC.Collect(0)
End If
objTest2.ReadFileWithoutPromotion()
Next
CurrentTime = DateTime.Now
Console.WriteLine(String.Format("Time taken without promotion:
{0}:{1}", CurrentTime.Subtract(t).Seconds,
CurrentTime.Subtract(t).Milliseconds))
Console.WriteLine("File Read: {0} times",
TextFile._fileReadCount)
TextFile._fileReadCount = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
Console.ReadLine()
End Sub
End Module
Class TextFile
Public ReadOnly Filename As String
Private wrText As WeakReference
Public Shared _fileReadCount As Integer = 0
Public Sub New(ByVal filename As String)
Me.Filename = filename
End Sub
Public ReadOnly Property Contents() As String
Get
Dim txt As String
If Not (wrText Is Nothing) Then
' if the weakly referenced string is
' still there, return it to caller
txt = DirectCast(wrText.Target, String)
If Not (txt Is Nothing) Then _
Return txt
End If
' else we need to read (again) the file
Dim sr As System.IO.StreamReader
Try
_fileReadCount += 1
' read the entire file in one shot
sr = New System.IO.StreamReader(Filename)
txt = sr.ReadToEnd()
' create a weak-reference to it
' and return to main app
wrText = New WeakReference(txt)
Return txt
Finally
' close the stream if necessary
If Not (sr Is Nothing) Then _
sr.Close()
End Try
End Get
End Property
End Class
Public Class Test1
Dim objText As New TextFile("C:\Log.txt")
Private _flag As Boolean = False
Public Sub ReadFile()
Dim t As String = objText.Contents
If GC.GetGeneration(t) = 0 Then
GC.Collect(0)
Console.WriteLine("File Contents Promoted to Next
Generation")
End If
End Sub
Public Sub ReadFileWithoutPromotion()
Dim t As String = objText.Contents
End Sub
End Class
Problem:
For my utter surprise in the First iteration of first for loop when it
goes into Contents property and after reading the File, the generation
of the variable "txt" is 2.I cant solve this mystery.Can any1 pick out
what is happening.
Thanks and Regards
Saurabh Garg