Skip to content

Commit

Permalink
perf(snowflake): optimize Snowflake.timestampFrom (#792)
Browse files Browse the repository at this point in the history
* Optimize Snowflake.timestampFrom

* edit based on feedback
  • Loading branch information
advaith1 authored Sep 9, 2024
1 parent 63feeab commit b97b30c
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions packages/snowflake/src/lib/Snowflake.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const IncrementSymbol = Symbol('@sapphire/snowflake.increment');
const EpochSymbol = Symbol('@sapphire/snowflake.epoch');
const EpochNumberSymbol = Symbol('@sapphire/snowflake.epoch.number');
const ProcessIdSymbol = Symbol('@sapphire/snowflake.processId');
const WorkerIdSymbol = Symbol('@sapphire/snowflake.workerId');

Expand All @@ -18,6 +19,8 @@ export const MaximumProcessId = 0b11111n;
*/
export const MaximumIncrement = 0b111111111111n;

const TimestampFieldDivisor = 2 ** 22;

/**
* A class for generating and deconstructing Twitter snowflakes.
*
Expand All @@ -44,6 +47,12 @@ export class Snowflake {
*/
private readonly [EpochSymbol]: bigint;

/**
* Internal reference of the epoch passed in the constructor as a number
* @internal
*/
private readonly [EpochNumberSymbol]: number;

/**
* Internal incrementor for generating snowflakes
* @internal
Expand All @@ -67,15 +76,23 @@ export class Snowflake {
*/
public constructor(epoch: number | bigint | Date) {
this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);
this[EpochNumberSymbol] = Number(this[EpochSymbol]);
}

/**
* The epoch for this snowflake
* The epoch for this snowflake, as a bigint
*/
public get epoch(): bigint {
return this[EpochSymbol];
}

/**
* The epoch for this snowflake, as a number
*/
public get epochNumber(): number {
return this[EpochNumberSymbol];
}

/**
* Gets the configured process ID
*/
Expand Down Expand Up @@ -173,7 +190,7 @@ export class Snowflake {
* @returns The UNIX timestamp that is stored in `id`.
*/
public timestampFrom(id: string | bigint): number {
return Number((BigInt(id) >> 22n) + this[EpochSymbol]);
return Math.floor(Number(id) / TimestampFieldDivisor) + this[EpochNumberSymbol];
}

/**
Expand Down

0 comments on commit b97b30c

Please sign in to comment.