Quick comparison among UDTs

Quick comparison among UDTs

When you need to compare two User Defined Type (UDT) variables to check whether they are equal, the only approach that you can follow in plain VB is to compare each individual element of the UDT. For example, say that you have the following Type declaration:

Private Type MyUDT    item1 As Boolean    item2 As Long    item3 As Double    item4 As SingleEnd Type

and two MyUDT variables, udt1 and udt2. This code checks whether these variables contain the same values:

If udt1.item1 = udt2.item1 And udt1.item2 = udt2.item2 And udt1.item3 = _    udt2.item3 And udt1.item4 = udt2.item4 Then    MsgBox "Equal"Else    MsgBox "Different"End If

You can make your code faster if you manually adopt a short-circuit evaluation technique, so that unnecessary comparisons are never performed:

Dim equal As BooleanIf udt1.item1 = udt2.item1 Then     If udt1.item2 = udt2.item2 Then        If udt1.item3 = udt2.item3 Then             If udt1.item4 = udt2.item4 Then equal = True        End If    End IfEnd IfIf equal    MsgBox "Equal"Else    MsgBox "Different"End If

However, you trade code linearity with performance, and this approach can really be used for UDTs with more than just a few items.

A better approach is to move the contents of both UDTs into two strings, and then compare the strings. You need the CopyMemory API function to do so, and you must evaluate the exact number of bytes to be moved:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _    Any, source As Any, ByVal bytes As Long)' a sample UDT structure, that contains almost every possible type of dataPrivate Type MyUDT    item1 As Boolean    item2(10) As Integer    item3 As Long    item4 As Single    item5 As Double    item6 As Currency    item7 As String * 20End TypeDim udt1 As MyUDT, udt2 As MyUDT' init the first UDTudt1.item1 = 10udt1.item2(1) = 4udt1.item3 = 12345udt1.item4 = 345.567udt1.item5 = 111.333444udt1.item6 = 223344.5566udt1.item7 = "this is a test"' init the second UDT' (in this test both UDTs contains the same value)udt2 = udt1' the number of bytes to be comparedDim bytes As Longbytes = LenB(udt1)' the strings used for the comparisonDim s1 As String, s2 As String' make them long enough to host the UDTss1 = Space$((bytes + 1)  2)s2 = s1' copy the UDTs into the stringsCopyMemory ByVal StrPtr(s1), ByVal VarPtr(udt1), bytesCopyMemory ByVal StrPtr(s2), ByVal VarPtr(udt2), bytes' now you can perform the comparisonIf s1 = s2 Then    MsgBox "Equal"Else    MsgBox "Different"End IfEnd Sub

There are a few points you must keep in mind in order to use this technique correctly:

  • the UDT can contain only numeric items and fixed-length strings: it can’t contain variable-length strings or object references
  • The UDT can contain a static array of any type of data, except variable-length strings or object, but it can’t contain dynamically resized arrays: in other words, the number of elements must be established in the UDT declaration
  • You can only compare UDTs for equality: you can’t use this technique to decide whether a UDT is “greater” or “lesser” than another, whatever this might mean in your application
  • Fixed-length strings inside the UDT are compared in case-insensitive mode; you can’t use this technique to compare strings without making any distinction between character case.

devx-admin

devx-admin

Share the Post:
Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles