本文仅实现了一种理论上的管理已经创建ActiveX COM方法,部分代码可以直接使用,由于未进行性能及稳定性测试,所以不建议使用到实际生产环境。下面所述将以VBScript脚本语言为例,同样适用于ASP、VB及VBA(Visual Basic For Application)技术。
大家知道在VBScript中创建对象是通过CreateObject实现的,由于是对象类型,所以必须通过Set关键字进行对象引用,当对象使用完毕后要通过Set [对象名] = Nothing进行对象销毁,这样VBS内部对象引用计数才下降,直至完全销毁回收。
大部分情况下,我们所创建的对象是可以复用的,也就是说,我们在一次使用完毕后可以不用急于销毁对象,然后第二、三次继续使用这个已经存在的对象,这样就避免多次调用CreateObject带来性能上的损耗,以及可能创建失败的风险。
比如说有这样的WScript/VBScript代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| Function IsFileExists(filename)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
IsFileExists = fso.FileExists(filename)
Set fso = Nothing
End Function
Function IsFolderExists(filename)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
IsFolderExists = fso.FolderExists(filename)
Set fso = Nothing
End Function
Sub WriteTextFile(filename, text)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile(filename, true)
f.WriteLine text
f.Close
Set f = Nothing
Set fso = Nothing
End Sub
If Not IsFileExists("C:\test\data.txt") Then
If IsFolderExists("C:\test") Then
WriteTextFile "C:\test\data.txt", "Hello world!"
End If
End If |
Function IsFileExists(filename)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
IsFileExists = fso.FileExists(filename)
Set fso = Nothing
End Function Function IsFolderExists(filename)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
IsFolderExists = fso.FolderExists(filename)
Set fso = Nothing
End Function Sub WriteTextFile(filename, text)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile(filename, true)
f.WriteLine text
f.Close
Set f = Nothing
Set fso = Nothing
End Sub If Not IsFileExists("C:\test\data.txt") Then
If IsFolderExists("C:\test") Then
WriteTextFile "C:\test\data.txt", "Hello world!"
End If
End If
这里实现了一个简单的功能,判断文件data.txt,如果不存在,然后判断C:\test文件夹是否存在,存在的话就写入data.txt文件,简单的功能包含了“语法糖”般的函数调用,虽然这样做封装特性比较好,而且提升了我们编码的效率,但是我们这里创建了3次Scripting.FileSystemObject对象,因此程序执行的性能可想而知了,其实较好的做法是创建1次Scripting.FileSystemObject对象,然后FileExists、FolderExists以及CreateTextFile都属于上下文无关的方法,因此可以复用,所以有了下面2种办法:
继续阅读 →