Skip to content

Commit

Permalink
fs: improve mkdtemp performance for buffer prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Dec 6, 2023
1 parent 727dd28 commit 8df3dfe
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 17 deletions.
39 changes: 39 additions & 0 deletions benchmark/fs/bench-mkdtempSync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

const common = require('../common');
const fs = require('fs');
const tmpdir = require('../../test/common/tmpdir');

const bench = common.createBenchmark(main, {
type: ['valid-string', 'valid-buffer', 'invalid'],
n: [1e3],
});

function main({ n, type }) {
tmpdir.refresh();
let prefix;

switch (type) {
case 'valid-string':
prefix = tmpdir.resolve(`${Date.now()}`);
break;
case 'valid-buffer':
prefix = Buffer.from(tmpdir.resolve(`${Date.now()}`));
break;
case 'invalid':
prefix = tmpdir.resolve('non-existent', 'foo', 'bar');
break;
default:
new Error('Invalid type');
}

bench.start();
for (let i = 0; i < n; i++) {
try {
fs.mkdtempSync(prefix, { encoding: 'utf8' });
} catch {
// do nothing
}
}
bench.end(n);
}
19 changes: 2 additions & 17 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2950,16 +2950,9 @@ function mkdtemp(prefix, options, callback) {
prefix = getValidatedPath(prefix, 'prefix');
warnOnNonPortableTemplate(prefix);

let path;
if (typeof prefix === 'string') {
path = `${prefix}XXXXXX`;
} else {
path = Buffer.concat([prefix, Buffer.from('XXXXXX')]);
}

const req = new FSReqCallback();
req.oncomplete = callback;
binding.mkdtemp(path, options.encoding, req);
binding.mkdtemp(prefix, options.encoding, req);
}

/**
Expand All @@ -2973,15 +2966,7 @@ function mkdtempSync(prefix, options) {

prefix = getValidatedPath(prefix, 'prefix');
warnOnNonPortableTemplate(prefix);

let path;
if (typeof prefix === 'string') {
path = `${prefix}XXXXXX`;
} else {
path = Buffer.concat([prefix, Buffer.from('XXXXXX')]);
}

return binding.mkdtemp(path, options.encoding);
return binding.mkdtemp(prefix, options.encoding);
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2748,6 +2748,11 @@ static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
CHECK_GE(argc, 2);

BufferValue tmpl(isolate, args[0]);
const char* ex = "XXXXXX";
const auto length = tmpl.length();
tmpl.AllocateSufficientStorage(length + strlen(ex));
snprintf(tmpl.out() + length, length, "%s", ex);

CHECK_NOT_NULL(*tmpl);
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kFileSystemWrite, tmpl.ToStringView());
Expand Down

0 comments on commit 8df3dfe

Please sign in to comment.